为什么Go泛型不支持将结构体作为返回值?

huangapple go评论110阅读模式
英文:

Why Go generics not support Struct as return value?

问题

Go版本是1.18-rc,这是我的代码:

  1. type Dog struct {
  2. Name string
  3. CanBark bool
  4. }
  5. type Cat struct {
  6. Name string
  7. CanClimb bool
  8. }
  9. type Pet interface {
  10. Dog | Cat
  11. }
  12. func GetDog[p Pet]() p {
  13. return Dog{
  14. Name: "Sam",
  15. CanBark: true,
  16. }
  17. }

当我运行代码时,我得到了消息“无法将(Dog字面量)(类型为Dog的值)用作返回值中的p值”。

英文:

Go version is 1.18-rc, here is my code:

  1. type Dog struct {
  2. Name string
  3. CanBark bool
  4. }
  5. type Cat struct {
  6. Name string
  7. CanClimb bool
  8. }
  9. type Pet interface {
  10. Dog | Cat
  11. }
  12. func GetDog

    () p {

  13. return Dog{

  14. Name: "Sam",

  15. CanBark: true,

  16. }

  17. }

when I run the code, I got the message "cannot use (Dog literal) (value of type Dog) as p value in return".

答案1

得分: 2

你不能直接返回为"Dog",它需要返回为"p"。

你应该检查类型,这样才能正常工作。

这是一个示例:

  1. func GetDog[p Pet]() p {
  2. a := new(p)
  3. i := any(a)
  4. switch i.(type) {
  5. case *Dog:
  6. v := Dog{"Sam", true}
  7. return any(v).(p)
  8. default:
  9. v := Cat{"Caty", true}
  10. return any(v).(p)
  11. }
  12. }

最后这是playground

英文:

You can't directly return as "Dog", it want "p"

You should check the type so that will work.

This is the example

  1. func GetDog[p Pet]() p {
  2. a := new(p)
  3. i := any(a)
  4. switch i.(type) {
  5. case *Dog:
  6. v := Dog{"Sam", true}
  7. return any(v).(p)
  8. default:
  9. v := Cat{"Caty", true}
  10. return any(v).(p)
  11. }
  12. }

and finally this is the playground

huangapple
  • 本文由 发表于 2022年2月22日 10:54:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/71215375.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定