Embedded Fields Access in Struct Types
In Go, structs can embed other structs as fields. This allows for the composition of complex data structures. However, accessing embedded field values can be confusing when using pointers.
Example and Issue
Consider the following struct definitions:
<code class="go">type Engine struct { power int } type Tires struct { number int } type Cars struct { *Engine Tires } </code>
In the Cars struct, an embedded pointer to the Engine struct (*Engine) is defined. When an instance of Cars is created as shown:
<code class="go">func main() { car := new(Cars) car.number = 4 car.power = 342 fmt.Println(car) } </code>
The program panics with the following error:
panic: runtime error: invalid memory address or nil pointer dereference [signal 0xb code=0x1 addr=0x0 pc=0x23bb]
Solution
To access an embedded field value, either an explicit field name or indirection through the embedded pointer is required. Here's an example of accessing the power field through indirection:
<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) car.power = 342 car.number = 4 fmt.Println(car) fmt.Println(car.Engine, car.power) fmt.Println(car.Tires, car.number) }</code>
This code successfully initializes the Cars instance, assigns values to embedded fields, and prints the expected output:
&{0x10328100 {4}} &{342} 342 {4} 4
The above is the detailed content of How to Avoid Runtime Errors When Accessing Embedded Fields in Go Structs with Pointers?. For more information, please follow other related articles on the PHP Chinese website!