As we all know, fields starting with capital letters are public fields, and fields starting with non-capital letters are private fields. But golang also supports anonymous fields. For example:
type myType struct { string }
These fields are designed for embedding. But is this field public or private?
If the type name of an embedded type is lowercase, it has package visibility. For example:
type t struct { string } func main() { x := t{} x.string = "a" fmt.println(x) }
However, if you move the 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 }
The above is the detailed content of Are Go struct anonymous fields public or private?. For more information, please follow other related articles on the PHP Chinese website!