我有一个界面
type FooInterface interface {
HasName() bool
}
它有一个我打算在 FooInterface 的其他实现中使用的基本实现
type FooBoilerplate struct {
hasName bool
}
func (f *FooBoilerplate) HasName() bool {
return f.hasName
}
像这样
type Foo1 struct {
fooId int
FooBoilerplate
}
func (f *Foo1) GetId() int {
return f.fooId
}
我想使用泛型为 FooInterface 创建一个容器类
type FooContainer[T FooInterface] struct {
list []T
}
func (fc *FooContainer[T]) AddItem() {
var t T
fc.list = append(fc.list, t)
}
但是,当我尝试实例化容器时出现编译错误
func RunThis() {
foo1 := Foo1{FooBoilerplate: FooBoilerplate{hasName: false}}
// works fine
TakesFooInterface(&foo1)
// doesnt compile
fc := FooContainer[Foo1]{}
fc.AddItem()
}
不确定为什么 Foo1 在传递给函数时被视为实现 FooInterface,但在传递给容器结构时却没有。我也不能将对象传递给容器实例化。
神不在的星期二
jeck猫
相关分类