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

Mary-Kate Olsen
Release: 2024-11-01 14:17:02
Original
309 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

Now, the code will compile and run successfully, producing the following output:

&{0x10328100 {4}}
&{342} 342
{4} 4
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!