Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct type embedded fields access

Tags:

go

I am trying to learn golang and at moment I am trying to understand pointers. I defined three struct type

type Engine struct {      
    power int             
}                         
                          
type Tires struct {       
    number int            
}                         
                          
                          
type Cars struct {           
    *Engine               
    Tires                 
}       

As you can see, in the Cars struct I defined an embedded type pointer *Engine. Look in the main.

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

                           
    

When I try to compile, I've got the following errors

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

How can I access the power field?

like image 945
softshipper Avatar asked Jul 20 '14 18:07

softshipper


2 Answers

For example,

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)
}

Output:

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

The unqualified type names Engine and Tires act as the field names of the respective anonymous fields.

The Go Programming Language Specification

Struct types

A field declared with a type but no explicit field name is an anonymous field, also called an embedded field or an embedding of the type in the struct. An embedded type must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type. The unqualified type name acts as the field name.

like image 153
peterSO Avatar answered Sep 30 '22 19:09

peterSO


Try this:

type Engine struct {      
    power int             
}                         

type Tires struct {       
    number int            
}                         


type Cars struct {           
    Engine               
    Tires                 
}

and than:

car := Cars{Engine{5}, Tires{10}}
fmt.Println(car.number)
fmt.Println(car.power)

http://play.golang.org/p/_4UFFB7OVI


If you want a pointer to the Engine, you must initialize your Car structure as:

car := Cars{&Engine{5}, Tires{10}}
fmt.Println(car.number)
fmt.Println(car.power)
like image 29
0xAX Avatar answered Sep 30 '22 20:09

0xAX