struct type anonymous fields access

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.


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)

Tags:

Go