gpt4 book ai didi

go - 如何在 slice 中附加不同的功能但相同的接口(interface)

转载 作者:数据小太阳 更新时间:2023-10-29 03:30:45 27 4
gpt4 key购买 nike

我试图附加可以用相同界面表示的不同功能。函数返回不同的对象但相同的接口(interface)。它失败并出现错误 cannot use Test (value of type func() *Dog) as func() Animal value in argument to append (typecheck)我应该怎么办?提前致谢!

package main

type Dog struct {
Word string
}

type Cat struct {
Word string
}

func (d *Dog) Say() string {
return d.Word
}

func (c *Cat) Say() string {
return c.Word
}

type Animal interface {
Say() string
}

func main() {
funcs := []func() Animal{}
funcs = append(funcs, Test) // error| cannot use Test (value of type func() *Dog) as func() Animal value in argument to append (typecheck)
}

func Test() *Dog {
return &Dog{Word: "dog"}
}

func Test2() *Cat {
return &Cat{Word: "cat"}
}

最佳答案

将您的函数更改为将 Animal 作为它们的返回类型。 func() *Dog 不能转换为 func() Animal,它们是两种不同的数据类型。

类似于您可以将 int 作为 interface{} 而不是 []int 作为 []接口(interface){}

关于go - 如何在 slice 中附加不同的功能但相同的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57427651/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com