Home  >  Article  >  Backend Development  >  How to Avoid Compilation Errors When Accessing Embedded Struct Fields in Go?

How to Avoid Compilation Errors When Accessing Embedded Struct Fields in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-10-27 10:28:30256browse

How to Avoid Compilation Errors When Accessing Embedded Struct Fields in Go?

Embedded Struct Type Field Access

When defining new struct types, it is possible to embed other structs as fields. This can be useful for creating complex data structures or inheriting functionality. However, accessing embedded struct fields can sometimes lead to compilation errors due to pointer handling.

Consider the following code:

<code class="go">type Engine struct {
    power int
}

type Tires struct {
    number int
}

type Cars struct {
    *Engine
    Tires
}

func main() {
    car := new(Cars)
    car.number = 4
    car.power = 342
    fmt.Println(car)
}</code>

This code attempts to embed an Engine struct as a pointer field (*Engine) in the Cars struct. While the syntax is correct, compiling the code results in the following error:

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x23bb]

To resolve this issue, it is necessary to correctly initialize the embedded Engine field. This can be achieved using pointers to the embedded struct:

<code class="go">func main() {
    car := new(Cars)
    car.Engine = new(Engine) // Initialize the Engine pointer
    car.power = 342
    car.number = 4
    fmt.Println(car)
}</code>

Now, the code compiles successfully and accesses the embedded field "power" without encountering any errors.

The above is the detailed content of How to Avoid Compilation Errors When Accessing Embedded Struct Fields in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn