Are pointers dereferenced by default in golang build methods?

I am confused by golang methods for structs. I follow in the textbook in which they are:

func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } 

From my understanding, p is a pointer, and you will need to dereference the pointer before you get the property, for example:

 filename := (*p).Title + ".txt" 

The only way that makes sense to me is that the dot acts like -> in C ++. What am I missing?

+7
pointers go
source share
2 answers

Yes, a pointer to a structure is automatically dereferenced. From spec on selectors :

For selectors, the following rules apply:

  • For a value x type T or *T , where T not a pointer or type of interface, xf denotes a field or method at the shallowest depth in T where such f exists. If there is no single f with shallow depth, the expression of the selector is illegal.

...

  1. As an exception, if type x is a named pointer type, and (*x).f is a valid selector expression representing a field (but not a method), xf is short for (*x).f .

Therefore, the following two statements are the same (with the first preferred):

 filename := p.Title + ".txt" filename := (*p).Title + ".txt" 
+16
source share

You do not need to specify pointers or use a special access operator to access the structure fields in Go.

 myRef := &ILikeCompositeLiteralInitilization{} fmt.Println(myRef.Dereferenced); 

functionally equivalent to:

 fmt.Printn((*myRef).Dereferenced); 

It may be worth noting that the behavior for functions is wrong. Sense, I would need to dereference the method that gets the type - this is the value, not the pointer. IE

 func (*ILikeCompositeLiteralInitilization) PointerVersion() func (ILikeCompositeLiteralInitilization) ValueVersion() myRef.PointerVersion() // compiler likes this myRef.ValueVersion() // won't compile (*myRef).ValueVersion() // compiler is OK with this 

Basically, with functions that do not have an implicit dereference or type operation address, your code will not compile.

+1
source share

All Articles