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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With