Reputation: 34099
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?
Upvotes: 7
Views: 4189
Reputation: 29
One more example, in case of not unique field names
package embeded
import "fmt"
type Engine struct {
id int
power int
}
type Tires struct {
id int
number int
}
type Cars struct {
id int
Engine
Tires
}
func Embed() Cars {
car := Cars{
id: 3,
Engine: Engine{id: 1, power: 5},
Tires: Tires{id: 2, number: 10},
}
fmt.Println(car.number)
fmt.Println(car.power)
fmt.Println(car.id)
fmt.Println(car.Engine.id)
fmt.Println(car.Tires.id)
return car
}
Upvotes: 0
Reputation: 166845
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
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.
Upvotes: 10
Reputation: 21837
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)
Upvotes: 8