为什么GO不允许将一个通用名称分配给另一个通用名称? [英] Why does Go not allow assigning one generic to another?

查看:0
本文介绍了为什么GO不允许将一个通用名称分配给另一个通用名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码引发编译错误

无法将ExampleProps(Props[Example]类型的变量)用作Return语句中的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]不是同一类型,并且您不能在需要使用一种类型的值的地方使用另一种类型的值。如果用作参数的类型本身满足某些赋值条件(例如接口和实现器),这并不重要。

简而言之,就好像您使用的是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

这篇关于为什么GO不允许将一个通用名称分配给另一个通用名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆