Home >Backend Development >Golang >How to Access Embedded Fields in Go Structs When Using Pointers?

How to Access Embedded Fields in Go Structs When Using Pointers?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 14:17:02399browse

How to Access Embedded Fields in Go Structs When Using Pointers?

Struct Type Embedded Fields Access

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!

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