go method and language pointer value method, the method of thinking led to the string

To see such a face questions in public https://mp.weixin.qq.com/s/9G3KQwXqQf56b8IQ7Tyysw number [Network] in the Chinese language Go
Example1
type Orange struct {
   Quantity int
}

func (o *Orange) Increase(n int) {
   o.Quantity += n
}

func (o *Orange) Decrease(n int) {
   o.Quantity -= n
}

func (o *Orange) String() string {
   return fmt.Sprintf("aaaa %#v", o.Quantity)
}

func main() {
   orange := &Orange{}
   orange.Increase(10)
   orange.Decrease(5)
   fmt.Println(orange)
}
 
Method first described the difference between the pointer value and the method:
Method pointer: Increase the above methods e.g., from reference types * Orange pointer type, such as the method of this form of the constructed reference pointer method
Value: Method type is a normal type of reference, as func (o Orange) Decrease (n int) {} The method of this form of the value
If the methods are value method
Example2
type Orange struct {
   Quantity int
}

func (o Orange) Increase(n int) {
   o.Quantity += n
}

func (o Orange) Decrease(n int) {
   o.Quantity -= n
}

func (o Orange) String() string {
   return fmt.Sprintf("aaaa %#v", o.Quantity)
}

func main() {
   was orange Orange
   orange.Increase(10)
   orange.Decrease(5)
   fmt.Println(orange)
}
The method will be executed inside output 5 String
If the method is a method pointer
Example3
type Orange struct {
   Quantity int
}

func (o *Orange) Increase(n int) {
   o.Quantity += n
}

func (o *Orange) Decrease(n int) {
   o.Quantity -= n
}

func (o *Orange) String() string {
   return fmt.Sprintf("aaaa %#v", o.Quantity)
}

func main() {
   was orange Orange
   orange.Increase(10)
   orange.Decrease(5)
   fmt.Println(orange)
}
Not execute string method in this case
Whether this will perform string method, you need to think about why would execute String methods, beginning when I saw this question, wondering why it is not called String method, it will call the String method, then suddenly think of is to go native String one way, when you call the default implementation of this method, when writing a String method, String method of covering a go, it will be the default execution method. Understand the problem, let's start will not say why Example3 execute String methods, because the reference pointer of type String type, and orange for the struct type, default will not be executed, is defined as when the orange orange: = & Orange, orange pointer type, That type of address.

Guess you like

Origin www.cnblogs.com/pig1314/p/11977654.html