dushaoshuai / dushaoshuai.github.io

https://www.shuai.host
0 stars 0 forks source link

Go: 使用 interface literal 来检查接口类型变量的动态类型是否实现了某个方法 #8

Open dushaoshuai opened 2 years ago

dushaoshuai commented 2 years ago

interface literal 的写法

interface {
    ... method set ...
}

使用 Type assertions

// iface 是一个接口类型的变量
if foo, ok := iface.(interface { ... method set ... }); ok {
    ... use methods ...
}

使用 Type switches

// iface 是一个接口类型的变量
switch x := iface.(type) {
case interface{ ... method set ... }:
    ... use methods ...
case interface{ ... method set ... }:
    ... use methods ...
default:
    ... do something ...
}

这种写法的一些参考