如何让泛型在接口和指针接收者上起作用
我在尝试用一个泛型函数来创建一个符合指定接口的值。
它不会编译,因为其中一个方法使用指针接收者。
Code:
package main
// implyType is one of many types that may be used with the generic function.
type implType struct {
value string
}
func (s implType) Get() string {
return s.value
}
func (s *implType) Set(v string) {
s.value = v
}
type stringGetSetter interface {
Get() string
Set(string)
}
func makeZero[T stringGetSetter]() T {
var value T
return value
}
func main() {
value := makeZero[implType]()
_ = value
}
这段代码编译失败,错误如下:
./main.go:27:20: implType does not satisfy stringGetSetter (method Set has pointer receiver)
这是一个简化的示例,用来展示这个问题。
解决方案
所以在此之中,Go将确保 T 本身实现了 stringGetSetter,在你的情况中是在第 makeZero[implType 行,编译器会检查 implType 是否实现了 stringGetSetter,答案并没有实现,因此出现错误,因为setter只作用于指向 implType 的指针,而不仅仅是 implType,因此 implType 并没有实现 stringGetSetter,只有 *implType 实现了。
你有几种解决方案,因此如果确实需要进行变更,接口应该由指针类型来实现,也就是说:
value := makeZero[*implType]()
...
简单来说,你有一个带有变异方法的接口,但类型参数不是指针——通常情况下,它们应该是指针。这是Go语言的预期行为。
或者,你可以把你的setter改成像下面这样:
func (s implType) Set(v string) implType {
s.value = v;
return s
}
如果你不想在变更方法中使用指针实现。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。