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

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

Why Go generics not support Struct as return value?

问题

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值”。

英文:

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

type Dog struct {
	Name    string
	CanBark bool
}

type Cat struct {
	Name     string
	CanClimb bool
}

type Pet interface {
	Dog | Cat
}

func GetDog

() p { return Dog{ Name: "Sam", CanBark: true, } }

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"。

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

这是一个示例:

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

英文:

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

You should check the type so that will work.

This is the example

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)
	}
}

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:

确定