为什么 Go 泛型不支持 Struct 作为返回值?
时间:2024-04-14
浏览:421
作者:佚名
知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《为什么 Go 泛型不支持 Struct 作为返回值?》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!
问题内容
go版本是1.18-rc,这是我的代码:
type Dog struct {
Name string
CanBark bool
}
type Cat struct {
Name string
CanClimb bool
}
type Pet interface {
Dog | Cat
}
func GetDog[p Pet]() p {
return Dog{
Name: "Sam",
CanBark: true,
}
}
当我运行代码时,我收到消息“无法使用(dog 文字)(dog 类型的值)作为返回的 p 值”。
正确答案
你不能直接返回“dog”,它需要“p”
您应该检查类型以便它可以工作。
这是例子
func GetDog[p Pet]() p {
a := new(p)
i := any(a)
switch i.(type) {
case *Dog:
v := Dog{"Sam", true}
return any(v).(p)
default:
v := Cat{"Caty", true}
return any(v).(p)
}
}
最后是 playground
本篇关于《为什么 Go 泛型不支持 Struct 作为返回值?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
