Is Go struct anonymous field public or private?

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

Is Go struct anonymous field public or private?

问题

我们知道,以大写字母开头的字段是公共的,而以小写字母开头的字段是私有的。但是Golang也支持匿名字段。例如:

type myType struct {
  string
}

这些字段是为了嵌入而设计的。但是这个字段是公共的还是私有的?

英文:

As we know, fields start with capital letters are public, and those are not are private. But Golang also support anonymous field. For example:

type myType struct {
  string
}

These fields are design for Embedding. But is this field public or private?

答案1

得分: 5

根据结构类型的规范:

声明了类型但没有显式字段名的字段被称为嵌入字段。嵌入字段必须被指定为类型名T或非接口类型名*T的指针,并且T本身不能是指针类型。未限定的类型名充当字段名。

string未限定名称string

根据导出标识符的规范:

为了允许从另一个包中访问标识符,可以将其导出。如果满足以下两个条件,则标识符被导出:

  1. 标识符名称的第一个字符是Unicode大写字母(Unicode字符类别为Lu);
  2. 标识符在包块中声明,或者它是字段名或方法名。

string的第一个字符不是Unicode大写字母。

由此可见,嵌入字段未被导出,换句话说,它对包是私有的。

英文:

From the specification on struct types:

> A field declared with a type but no explicit field name is called an embedded field. An embedded field must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type. The unqualified type name acts as the field name.

The unqualified name of string is string.

From the specification on exported identifiers:

> An identifier may be exported to permit access to it from another package. An identifier is exported if both:
> 1. the first character of the identifier's name is a Unicode uppercase letter (Unicode character category Lu); and
> 1. the identifier is declared in the package block or it is a field name or method name.

The first character of string is not a Unicode uppercase letter.

It follows that the embedded field is not exported. In other words, it's private to the package.

答案2

得分: 3

如果嵌入类型的类型名称是小写字母开头的,它具有包可见性。例如:

type T struct {
	string
}

func main() {
	x := T{}
	x.string = "a"
	fmt.Println(x)
}

然而,如果你将类型 T 移动到另一个包 p 中:

package p

type T struct {
  string
}
package main

import "testmod/p"

func main() {
    x := p.T{}
    x.string = "a" // 错误
}
英文:

If the typename of the embedded type is lower case, it has package visibility. For example:

type T struct {
	string
}

func main() {
	x := T{}
	x.string = "a"
	fmt.Println(x)
}

However if you move type T to another package p:

package p

type T struct {
  string
}

package main

import "testmod/p"

func main() {
    x := p.T{}
    x.string = "a" // Error
}


</details>



huangapple
  • 本文由 发表于 2023年4月27日 10:25:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76116304.html
匿名

发表评论

匿名网友

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

确定