Reputation: 900
I think I am missing a part of technical background. But I don't get, why I have to use an * to access the value of a simple pointer, but not for accessing values of a struct.
For example with a simple value:
func main() {
i := 42
p := &i
*p = 21 // <<< I have to use an asterisk to access the value
// ...
}
And a example with a struct:
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
p := &v
p.X = 1e9 // <<< I do not have to use an asterisk
// ...
}
(yes, the samples are from the official go lang tour here: https://go-tour-de.appspot.com/moretypes/4)
Just from my thoughts I would expect something like this
*p.X = 1e9
or (yeah, this would be somewhat strange)
p.*X = 1e9
So, why don't I have to use an asterisk to access struct pointer?
Upvotes: 2
Views: 659
Reputation: 18567
The official Golang tour where you found that example [here] explicitly says:
To access the field
X
of a struct when we have the struct pointerp
we could write(*p).X
. However, that notation is cumbersome, so the language permits us instead to write justp.X
, without the explicit dereference.
Upvotes: 6