In Go, struct types can contain embedded fields, which allow for embedding one or more types within a struct. This powerful feature enables code reuse and efficient memory management. However, understanding how to access these fields can be challenging while learning about pointers.
Consider the following struct definitions:
type Engine struct {
power int
}
type Tires struct {
number int
}
type Cars struct {
*Engine // Embedded field with pointer
Tires // Embedded field without pointer
}
As you've observed, within the Cars struct, an embedded type pointer *Engine is defined. This allows access to the Engine type's methods and fields via the Cars struct.
To access the power field of the Engine embedded field, you must first initialize both the Engine and Cars structs. In the main function:
func main() {
car := new(Cars) // Initialize Cars struct
car.Engine = new(Engine) // Initialize Engine struct explicitly
car.power = 342 // Set power field
car.number = 4 // Set number field
}
By explicitly initializing both structs, you establish a connection between the embedded *Engine pointer and the actual Engine object. Now, you can access the power field through the Cars struct:
fmt.Println(car.power) // Prints 342
Similarly, for the non-pointer embedded field Tires, you can directly access its number field:
fmt.Println(car.number) // Prints 4
This example demonstrates how to properly initialize and access embedded fields within a struct, enabling you to fully utilize code reuse and efficient memory management.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3