英文:
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
。
根据导出标识符的规范:
为了允许从另一个包中访问标识符,可以将其导出。如果满足以下两个条件,则标识符被导出:
- 标识符名称的第一个字符是Unicode大写字母(Unicode字符类别为Lu);
- 标识符在包块中声明,或者它是字段名或方法名。
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论