Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are pointers dereferenced by default inside of methods?

Tags:

pointers

go

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?

like image 766
m0meni Avatar asked Jun 11 '15 16:06

m0meni


People also ask

What is dereferenced pointer?

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.

How is * used to dereference pointers?

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.

What happens if you dereference a function pointer?

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.

Which operator is used to dereferencing pointer?

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 (*).


1 Answers

Yes, the pointer to the struct is automatically dereferenced. From the spec on selectors:

The following rules apply to selectors:

  1. For a value x of type T or *T where T is not a pointer or interface type, x.f denotes the field or method at the shallowest depth in T where there is such an f. If there is not exactly one f with shallowest depth, the selector expression is illegal.

...

  1. 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"
like image 132
Tim Cooper Avatar answered Nov 09 '22 04:11

Tim Cooper