Anonymous Fields in Go Structs
Anonymous fields in Go structs provide a unique way to embed the fields of another type into the current struct without explicitly naming them. It allows for code reuse, composition, and flexibility in data organization.
In the example you provided:
type myType struct { string }
string is an anonymous field in the myType struct. When you create an instance of myType, the anonymous field is internally named string (this can be seen in debugging tools).
Accessing Anonymous Fields
Unlike named fields, which can be accessed directly using dot notation (e.g., obj.name), anonymous fields cannot be accessed by their anonymous names. However, they provide a unique property known as "field promotion."
The first anonymous field in a struct is automatically promoted and becomes accessible as a direct field of the parent struct. This means that you can access the string field of myType using obj.string.
For example, in the following code:
func main() { obj := myType{"Hello World"} fmt.Println(obj) // Prints "Hello World" }
The fmt.Println statement prints the value of the string anonymous field, which is accessible as obj.string.
Benefits of Anonymous Fields
The above is the detailed content of How Do Anonymous Fields in Go Structs Work?. For more information, please follow other related articles on the PHP Chinese website!