This is a creation in Article, where the information may have evolved or changed.
Just started Golang, probably figured out the concept of method in go.
Most of the following rewrite the code for the handling process.
Methods can add (declare) a method to a type, for example:
type Cat struct {}func (c Cat) Hwo() { fmt.Println("Miah!")}
That is, add the Hwo method to the cat type (struct) so that it can emit sound when it barks.
This method of adding code behaves much better than Java (extend), and is better than python (you need to re-declare a class).
According to the official spec can correspond to the above example of the two statements:
func (c Cat) Hwo()func (c *Cat) Hwo()
What is the difference between these two?
package mainimport ( "fmt")type Cat struct { age int}func (c Cat) AddAge() { fmt.Println("add age!") fmt.Println(c.age + 10) c.age += 1}func (c *Cat) AddOneAge() { c.age += 1 fmt.Println("add one age!")}func main() { cat := &Cat{1} fmt.Println(cat) cat.AddAge() fmt.Println(cat) cat.AddOneAge() fmt.Println(cat)}
Results:
&{1}add age!11&{1}add one age!&{2}
Modify the Cat declaration method to
cat := Cat{1}
Results:
{1}add age!11{1}add one age!{2}
What happened?
The 1.CAT variable is a pointer that can be used with reflect. Typeof (cat) look out;
2. (c Cat) The added method Addage () is executed, which can get the value of cat, but does not change the value of the memory block pointed to by the cat pointer;
3. (c *cat) The added method Addoneage () is executed, changing the value of the memory block pointed to by the Cat pointer;
4. Redefine CATB: = Cat{1}, which seems to catb a non-pointer, but still the same result (except for the variables section).
How to interpret?
1. Whether a variable is declared as a pointer or a non-pointer, go has a consistent attitude towards them on method;
2. When declaring method, the incoming (C *cat) Declaration method can modify the new object (cat: =) because the processing object of method is a Cat type pointer.
3. When declaring a variable, it is recommended to declare it as a pointer object Cat: = &cat{1}, which is beneficial
A. Passing pointers are fruitful, especially when passing large variables
B. Most of the scientific code is to pass pointers, and for code consistency it is best to use pointers
See REFERENCE.3
Off-topic, here's an example of a situation that can be clarified
For interface, the identification method distinguishes between (c Cat) and (c *cat):
Http://play.golang.org/p/-g44WHg_uT
Reference
1.http://nathanleclaire.com/blog/2014/08/09/dont-get-bitten-by-pointer-vs-non-pointer-method-receivers-in-golang/
2.http://golang.org/ref/spec#method_declarations
3.http://golang.org/doc/faq#methods_on_values_or_pointers