Access anonymous fields of structure type

I am trying to recognize the golangs, and at the moment I am trying to understand the pointers. I defined three types of structure

type Engine struct {      
    power int             
}                         

type Tires struct {       
    number int            
}                         


type Cars struct {           
    *Engine               
    Tires                 
}       

As you can see, in the Cars structure I defined an anonymous 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 have 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?

+4
source share
2 answers

Try the following:

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 Engine, you must initialize the structure Caras follows:

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

For instance,

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

Conclusion:

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

Engine Tires .

Go

, , , , struct. T * T, T . .

+4

All Articles