What is a pointer

What is a pointer

0.5 Why Pointers

Why do we have Pointers

  1. To transfer data
  2. Shared data
  3. Reference, you can change the value and point to a different address

Use cases

  1. Value passing/sharing: Passing variables by reference
  2. Shared: Object is pointer data, assigned a=b a, B shares a memory space. Non-pointer variable values are copied.

1. Understanding of go language Pointers

2. Use of go language pointer

Go implicit conversion to pointer type 2. Receiver 3. Value method 4. Pointer to the method

The method involves two knowledge points:

  1. The difference between the pointer method and the value method is that the structure is passed by value. The value method is a copy of the method. Changes to the structure in the method are not reflected in the original method

Struct types (and all custom types) can call all value methods, and pointer types can call all value methods and pointer methods. But actually the GO language translates (or implicitly), which is a struct type that can call pointer methods. In the following example, r.rea () equals &r.rea ().

package main

import (
	"fmt"
)

type rectangle struct {
	width, height int
}

func (r *rectangle) area() int {
	return r.width * r.height
}
func (r rectangle) perim() int {
	return 2*r.width + 2*r.height
}
func main() {
	r := rectangle{10, 5}
	fmt.Println(r.area())
	fmt.Println(r.perim())
	p := &r
	fmt.Println(p.area())
	fmt.Println(p.perim())

}

Copy the code

Interface implementation: If a structure method has a pointer receiver, but the base type of the call is non-pointer, it does not implement the pointer method in the interface

Removes the syntactic sugar for automatically fetching addresses from primitive method calls

knowledge

  1. Assigning a variable to another variable (including an interface type variable) is a value copy, which in the case of an interface type variable contains a copy of the original variable’s value
package main

import (
	"fmt"
)

type shape interface {
	area() int
	perim() int
}

type rectangle struct {
	width, height int
}

func (r *rectangle) area() int {
	return r.width * r.height
}
func (r rectangle) perim() int {
	return 2*r.width + 2*r.height
}
func main() {
	var newr shape = &rectangle{width: 10, height: 5}
	fmt.Println(newr.area())
	fmt.Println(newr.perim())
	
	//r := rectangle{10, 5}
	//fmt.Println(r.area())
	//fmt.Println(r.perim())
	//p := &r
	//fmt.Println(p.area())
	//fmt.Println(p.perim())

}
Copy the code

Reference documentation: Efficient GO programming