相关疑难解决方法(0)

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

以下代码会引发编译错误

不能在 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
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:作为Example实现Generic,为什么Go不允许分配Props[Example]Props[Generic]

generics instantiation variable-assignment go

5
推荐指数
1
解决办法
3777
查看次数

标签 统计

generics ×1

go ×1

instantiation ×1

variable-assignment ×1