Home  >  Article  >  Backend Development  >  How Do You Access Embedded Struct Fields in Go When They Are Pointers?

How Do You Access Embedded Struct Fields in Go When They Are Pointers?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 21:55:02329browse

How Do You Access Embedded Struct Fields in Go When They Are Pointers?

Accessing Embedded Struct Fields

In Go, structs can have embedded fields, which allow one struct to reuse fields from another struct. However, accessing these embedded fields can sometimes lead to confusion.

Consider the following code:

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

type Tires struct {
    number int
}

type Cars struct {
    *Engine  // embedded pointer-to-struct field
    Tires
}

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

Upon compilation, you may encounter the error:

runtime error: invalid memory address or nil pointer dereference

Understanding Embedded Fields

To access the power field in the embedded Engine struct, you cannot use car.power directly. Embedded fields are accessed indirectly through an intermediate pointer or value.

Solution

One way to resolve the error is by assigning a new Engine to the embedded field in the Cars struct:

<code class="go">package main

import "fmt"

type Engine struct {
    power int
}

type Tires struct {
    number int
}

type Cars struct {
    *Engine  // embedded pointer-to-struct field
    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>

Output

&{0x10328100 {4}}
&{342} 342
{4} 4

In this modified code, car.Engine now points to a valid Engine struct, allowing you to access the power field.

Note: You can also access embedded fields using reflection or other advanced techniques, but the above approach is generally the most straightforward.

The above is the detailed content of How Do You Access Embedded Struct Fields in Go When They Are 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