Golang中如何获取接口的正确底层类型
Golang中如何获取接口的正确底层类型
我正在尝试找出传递给接口的具体类型。该接口由两种 struct 类型实现。
type T interface {
hello()
}
type foo struct{}
func (f *foo) hello() {}
type boo struct{}
func (b *boo) hello() {}
func main() {
abc(&foo{})
abc(&boo{})
}
func abc(t T) {
switch t {
case &foo{}:
fmt.Println("foo")
case &boo{}:
fmt.Println("boo")
default:
fmt.Println("NOTHING")
}
}
这段代码总是输出 "NOTHING" 和 "NOTHING"。
有人能帮我澄清一下我遗漏了什么吗?
完整代码链接:Go Playground - The Go Programming Language
更多关于Golang中如何获取接口的正确底层类型的实战教程也可以访问 https://www.itying.com/category-94-b0.html
4 回复
foo{} 是一个值,你需要的是一个类型,具体到你的情况是 *foo。
尝试使用类型断言:
func abc(t T) {
switch t.(type) {
case foo{}:
fmt.Println("foo")
case boo{}:
fmt.Println("boo")
default:
fmt.Println("NOTHING")
}
}
我遇到了一个编译时错误:
Impossible type switch case: 'foo' does not implement 'T' 和
Impossible type switch case: 'boo' does not implement 'T'
在Go中,使用switch语句进行类型断言时,不能直接比较结构体实例,因为&foo{}和&boo{}会创建新的指针,与传入的接口值持有的指针不同。你需要使用类型断言来检查接口的具体类型。
以下是修正后的代码:
package main
import "fmt"
type T interface {
hello()
}
type foo struct{}
func (f *foo) hello() {}
type boo struct{}
func (b *boo) hello() {}
func main() {
abc(&foo{})
abc(&boo{})
}
func abc(t T) {
switch v := t.(type) {
case *foo:
fmt.Println("foo")
case *boo:
fmt.Println("boo")
default:
fmt.Printf("NOTHING: %T\n", v)
}
}
或者,如果你只需要检查特定类型,可以使用类型断言:
func abc(t T) {
if _, ok := t.(*foo); ok {
fmt.Println("foo")
} else if _, ok := t.(*boo); ok {
fmt.Println("boo")
} else {
fmt.Println("NOTHING")
}
}
类型开关(type switch)是获取接口底层类型最直接的方法,它通过t.(type)在switch语句中检查接口值的动态类型。

