首页 >后端开发 >Golang >为什么我不能在 Go 泛型中将 `Props[Example]` 分配给 `Props[Generic]` ?

为什么我不能在 Go 泛型中将 `Props[Example]` 分配给 `Props[Generic]` ?

Susan Sarandon
Susan Sarandon原创
2024-12-20 09:15:11440浏览

Why Can't I Assign `Props[Example]` to `Props[Generic]` in Go Generics?

通用类型赋值限制

考虑以下代码:

type Generic interface {
    ID() string
}

type Props[G Generic] struct{}

type Example struct {
    id string
}

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

var ExampleProps = Props[Example]{}

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

此代码无法编译并出现错误:

cannot use ExampleProps (variable of type Props[Example]) as Props[Generic] value in return statement

这是为什么发生?

Go 泛型在使用不同类型参数实例化时会创建全新的命名类型。在这种情况下,Props[Example] 和 Props[Generic] 是不同的命名类型,即使 Example 实现了 Generic。

通过类型参数化实现灵活性

解决此问题并保持灵活性,可以使用类型参数实例化 Props:

func Problem[T Generic](v T) Props[T] {
    return Props[T]{Value: v}
}

这种方法允许函数为实现 Generic 的特定泛型类型 T 返回 Props[T]。

摘要

在 Go 泛型中,使用不同类型参数实例化泛型类型会导致不同的命名类型。因此,尝试将一种类型分配给另一种类型,即使它们的类型参数满足特定条件,也是不允许的。使用类型参数化提供了在此类场景中保持灵活性的解决方案。

以上是为什么我不能在 Go 泛型中将 `Props[Example]` 分配给 `Props[Generic]` ?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn