在方法声明中使用 _ 作为多个类型参数时出现“无法使用 .this”错误

Sam*_*ann 9 generics go

我正在使用 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)

为 T1 和 T2 实例化具有相同类型的 Foo

_Foo如果使用相同类型实例化(例如,string对于T1T2),也适用于方法声明:

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)

Sam*_*ann 3

正如问题评论中提到的,所描述的行为是 Go 1.18beta1 中的一个错误,并由问题 50419进行跟踪。

编辑

我已确认该错误已在2022 年 1 月 31 日发布的1.18beta2中修复。