我正在使用 Go 来处理类型参数(泛型)1.18beta1。
考虑以下片段:
package main
import (
"fmt"
)
func main() {
foo := &Foo[string, int]{
valueA: "i am a string",
valueB: 123,
}
fmt.Println(foo)
}
type Foo[T1 any, T2 any] struct {
valueA T1
valueB T2
}
func (f *Foo[_,_]) String() string {
return fmt.Sprintf("%v %v", f.valueA, f.valueB)
}
Run Code Online (Sandbox Code Playgroud)
此代码片段无法构建,并出现以下错误:
<autogenerated>:1: cannot use .this (type *Foo[string,int]) as type *Foo[go.shape.string_0,go.shape.string_0] in argument to (*Foo[go.shape.string_0,go.shape.int_1]).String
Run Code Online (Sandbox Code Playgroud)
_由于类型参数提案中的以下语句,我尝试在方法声明中使用:
方法声明中列出的类型参数不必与类型声明中的类型参数具有相同的名称。特别是,如果方法不使用它们,则它们可以是 _。
上面的构建错误是错误1.18beta1还是我遗漏了什么?
String如果我将方法声明更改为以下内容(_用实际类型参数替换),我可以成功构建代码:
<autogenerated>:1: cannot use .this (type *Foo[string,int]) as type *Foo[go.shape.string_0,go.shape.string_0] in argument to (*Foo[go.shape.string_0,go.shape.int_1]).String
Run Code Online (Sandbox Code Playgroud)
_当仅使用单个类型参数时,我成功地使用了:
func (f *Foo[T1,T2]) String() string {
return fmt.Sprintf("%v %v", f.valueA, f.valueB)
}
Run Code Online (Sandbox Code Playgroud)
_Foo如果使用相同类型实例化(例如,string对于T1和T2),也适用于方法声明:
package main
import (
"fmt"
)
func main() {
foo := &Foo[string]{"i am a string"}
fmt.Println(foo)
}
type Foo[T1 any] struct {
value T1
}
func (f *Foo[_]) String() string {
return fmt.Sprintf("%v", f.value)
}
Run Code Online (Sandbox Code Playgroud)