In my code below, why does *bikeSlice[0].Type
return to me the value of the Type
field instead of the memory address? How come *bikeSlice[0]
returns {Type:0xc0000641c0}
though *bikeSlice[0].Type
seems to automatically dereference the Type
field?
package main
import "fmt"
type Bike struct {
Type *string
}
func main() {
type1 := "road"
bike1 := Bike{
Type: &type1,
}
type2 := "mountain"
bike2 := Bike{
Type: &type2,
}
var bikeSlice []*Bike
bikeSlice = append(bikeSlice, &bike1)
bikeSlice = append(bikeSlice, &bike2)
fmt.Printf("%+v
", *bikeSlice[0])
fmt.Printf("%+v", *bikeSlice[0].Type)
}
Playground: https://play.golang.org/p/2Q4Bt60SUdW
Output:
{Type:0x40e128}
road
Yes I think it will automatically dereference. See https://golang.org/ref/spec#Selectors
I think rule number 3 is the one you're looking for:
As an exception, if the type of x is a defined pointer type and (*x).f is a valid selector expression denoting a field (but not a method), x.f is shorthand for (*x).f.