为什么一个泛型不能分配给另一个,即使它们的类型参数可以?

2023-12-22

以下代码会引发编译错误

不能在 return 语句中使用 ExampleProps(Props[Example] 类型的变量)作为 Props[Generic] 值

// Abstract
type Generic interface {
    ID() string
}

type Props[G Generic] struct{}

// Example
type Example struct {
    id string
}

func (example Example) ID() string {
    return example.id
}

var ExampleProps = Props[Example]{}

// Problem
func Problem() Props[Generic] {
    return ExampleProps
}

我的问题是:作为Example实施Generic,为什么Go不允许赋值Props[Example] to Props[Generic]?


使用不同类型参数实例化泛型类型会产生两个新的不同命名类型。

请注意,每次提供类型参数(包括在函数参数或返回类型中)时,您都在实例化泛型类型:

// Props is instantiated with type argument 'Generic'
func Problem() Props[Generic] {
    return ExampleProps
}

所以Props[Example]只是与以下类型不同Props[Generic]并且您不能在需要使用一种类型的值时使用另一种类型的值。用作参数的类型本身是否满足某些可分配性条件并不重要,例如接口和实现者。

对于实例化的泛型也是如此any。方式any只是另一个静态类型——别名interface{}。它不等于T并且它不等于“任何类型”。

简单来说,就好像您正在使用int where string是期待。

您可以修复它并保持一定的灵活性,那就是实例化Props带有类型参数——这是否有意义取决于您实际计划如何使用此函数。无论如何,作为演示:

// adding a field to make this a bit less contrived
type Props[G Generic] struct{ Value G }

// Props instantiated with T, adequately constrained
func Problem[T Generic](v T) Props[T] {
    return Props[T]{ Value: v }
}

func main() {
    a := Problem(Example{})
    fmt.Println(a)
}

操场:https://gotipplay.golang.org/p/wcDOtJ6z80u https://gotipplay.golang.org/p/wcDOtJ6z80u

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么一个泛型不能分配给另一个,即使它们的类型参数可以? 的相关文章

随机推荐