登录
首页 >  Golang >  Go问答

为何无法将一个泛型赋值给另一个,尽管它们的类型参数相容?

来源:stackoverflow

时间:2024-02-13 18:18:23 442浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《为何无法将一个泛型赋值给另一个,尽管它们的类型参数相容?》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

以下代码会引发编译错误

不能在 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] 分配给 props[generic]


正确答案


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

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

// props is instantiated with type argument 'generic'
func problem() props[generic] {
    return exampleprops
}

因此,props[example]props[generic] 的类型不同,并且您不能在需要使用一种类型的值时使用另一种类型的值。用作参数的类型本身是否满足某些可分配性条件并不重要,例如接口和实现器。

对于使用 any 实例化的泛型也是如此。类型 any 只是另一种静态类型 - interface{} 的别名。它不等于 t 也不等于“任何类型”。

简单来说,就好像您使用的是 int,其中需要 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

理论要掌握,实操不能落!以上关于《为何无法将一个泛型赋值给另一个,尽管它们的类型参数相容?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>