I'm confused by methods on structs in Go. I've following along in a tutorial in which they have:
func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
From my understanding, p
is pointer and you would need to dereference the pointer before retrieving a property for example:
filename := (*p).Title + ".txt"
The only way this makes sense to me is if the dot is acting like ->
in C++. What am I missing?
Dereference a pointer is used because of the following reasons: It can be used to access or manipulate the data stored at the memory location, which is pointed by the pointer. Any operation applied to the dereferenced pointer will directly affect the value of the variable that it points to.
Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers.
As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function pointer yields the referenced function, which can be invoked and passed arguments just as in a normal function call.
In computer programming, a dereference operator, also known as an indirection operator, operates on a pointer variable. It returns the location value, or l-value in memory pointed to by the variable's value. In the C programming language, the deference operator is denoted with an asterisk (*).
Yes, the pointer to the struct is automatically dereferenced. From the spec on selectors:
The following rules apply to selectors:
- For a value
x
of typeT
or*T
whereT
is not a pointer or interface type,x.f
denotes the field or method at the shallowest depth inT
where there is such anf
. If there is not exactly onef
with shallowest depth, the selector expression is illegal....
- As an exception, if the type of
x
is a named pointer type and(*x).f
is a valid selector expression denoting a field (but not a method),x.f
is shorthand for(*x).f
.
Therefore, the following two statements are the same (with the first being preferred):
filename := p.Title + ".txt"
filename := (*p).Title + ".txt"
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