How to initialize an array of anonymous struct with generic field

huangapple go评论73阅读模式
英文:

How to initialize an array of anonymous struct with generic field

问题

我想了解一下是否可以初始化一个包含泛型字段的匿名结构体数组。下面的代码无法编译,而且我找不到任何相关的示例:

testCases := type [K comparable, T Numeric] []struct   {
    name     string
    args     map[K]T
    expected int
}{
    // items ...
    {"integer", map[string]int{"a":1},
}

没有匿名结构体的话很容易实现,但不是你想要的:

type args[K comparable, T Numeric] struct {
    m map[K]T
}
testCases := []struct {
    name     string
    args     args[string, int]
    expected int
}{}

谢谢!

英文:

I'd to learn whether it's possible to initialize an array of anonymous struct contains generic-field. Code below doesn't compile, moreover I couldn't find any sample related to:

	testCases := type [K comparable, T Numeric] []struct   {
		name     string
		args     map[K]T
		expected int
	}{
        // items ...
        {"integer", map[string]int{ "a":1 },
    }

Without anonymous structs it's easy, but not the aimed:

	type args[K comparable, T Numeric] struct {
		m map[K]T
	}
	testCases := []struct {
		name     string
		args     args[string, int]
		expected int
	}{}

Thanks!

答案1

得分: 4

类型参数被引入,这样当你实例化类型时,可以给类型参数提供具体的类型。鉴于此,你想做的事情没有意义。你想创建一个通用的匿名类型并立即实例化它。你不能在其他地方使用这个匿名结构体(因为它是匿名的),所以省略类型参数,并使用你将实例化类型参数的具体类型。

至于回答你最初的问题:不,你不能这样做。语法不允许这样做。曾经有一个提案支持这个,但被拒绝了:proposal: spec: generics: Anonymous generic aggregate types #45591。解决方法是使用命名的结构体类型而不是匿名的结构体类型,就像你建议的那样。

英文:

Type parameters are introduced so when you instantiate the type, you can give concrete types to type parameters. Given that, there is no sense in what you want to do. You want to create a generic anonymous type and instantiate it right away. You can't use this anonymous struct elsewhere (because it's anonymous), so leave out the type parameters and use the concrete types you'd instantiate the type parameters with if it would be a named type.

And to answer your original question: no, you cannot do this. The syntax does not allow this. There was a proposal to support this but was rejected: proposal: spec: generics: Anonymous generic aggregate types #45591. The workaround is to use a named struct type instead of the anonymous struct type, just as you suggested.

huangapple
  • 本文由 发表于 2022年3月21日 01:30:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/71549047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定