英文:
Unnamed arrays in structs in Go
问题
所以我可以有
struct {
int
x []int
}
然而,
struct {
int
[]int
}
会导致一个syntax error: unexpected [, expecting }
。在Go语言中,是否有一种在结构体中使用无名数组的方法?如果有,正确的语法是什么?
英文:
So I can have
struct {
int
x []int
}
However,
struct {
int
[]int
}
will result in a syntax error: unexpected [, expecting }
. Is there a way of having unnamed arrays in structs in Go? If so, what's the correct syntax?
答案1
得分: 3
阅读Go编程语言规范。特别是关于结构类型的部分。Go术语用于描述您正在寻找的是匿名字段。
> 这样的[匿名]字段类型必须
> 被指定为类型名称T或类型名称*T的指针,而T
> 本身不能是指针类型。
int
是一个类型名称。[]int
既不是类型名称,也不是类型名称的指针。
英文:
Read The Go Programming Language Specification. In particular, the section on Struct types. The Go term to describe what you are looking for is an anonymous field.
> Such a[n] [anonymous] field type must
> be specified as a type name T or as a
> pointer to a type name *T, and T
> itself may not be a pointer type.
int
is a type name. []int
is neither a type name nor a pointer to a type name.
答案2
得分: 1
不,匿名字段的类型必须是类型名称或类型名称的指针。您可以声明一个与数组类型相同的新类型名称,然后它将起作用,但不完全相同。
英文:
No, the type of an anonymous field must be a type name or a pointer to a type name. You could declare a new type name that is the same as an array type, and then it would work, but it wouldn't be exactly the same.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论