How to Avoid Runtime Errors When Accessing Embedded Fields in Go Structs with Pointers?

DDD
Release: 2024-10-30 04:23:02
Original
932 people have browsed it

How to Avoid Runtime Errors When Accessing Embedded Fields in Go Structs with Pointers?

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

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

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

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

This code successfully initializes the Cars instance, assigns values to embedded fields, and prints the expected output:

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

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!

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
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!