在Go语言中,结构体中的未命名数组

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

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.

huangapple
  • 本文由 发表于 2010年6月28日 07:40:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/3129324.html
匿名

发表评论

匿名网友

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

确定