Home >Backend Development >Golang >How to Access Embedded Fields in Go Structs When Using Pointers?
In Go, structs can embed other struct types. However, accessing embedded fields can sometimes be a challenge for beginners. Consider the following code snippet:
<code class="go">type Engine struct { power int } type Tires struct { number int } type Cars struct { *Engine Tires }</code>
Here, the Cars struct embeds the *Engine pointer type. Attempting to compile the code results in the following error:
<code class="go">panic: runtime error: invalid memory address or nil pointer dereference [signal 0xb code=0x1 addr=0x0 pc=0x23bb]</code>
This error occurs because the Engine field in the Cars struct is a pointer and is initialized as nil. To access the power field of the embedded Engine, we need to explicitly initialize the Engine field:
<code class="go">package main import "fmt" type Engine struct { power int } type Tires struct { number int } type Cars struct { *Engine Tires } func main() { car := new(Cars) car.Engine = new(Engine) // Initialize the Engine field car.power = 342 car.number = 4 fmt.Println(car) fmt.Println(car.Engine, car.power) fmt.Println(car.Tires, car.number) }</code>
Now, the code will compile and run successfully, producing the following output:
&{0x10328100 {4}} &{342} 342 {4} 4
As you can see, we were able to access the power field of the embedded Engine struct by explicitly initializing the Engine field in the Cars struct. This is a common practice in Go when working with embedded structs.
The above is the detailed content of How to Access Embedded Fields in Go Structs When Using Pointers?. For more information, please follow other related articles on the PHP Chinese website!