So why does Golang need pointers? What unique uses can this kind of pointer have? (Recommended Learning: Go )
## When learning quoting the type language, you must always figure it out first, when you give a function/method to pass on Is it a value or a reference. In fact, in most reference languages, when the parameters are of basic types, most of the parameters passed in are values, which means another copy of the parameters is copied to the current function call stack. When the parameters are of advanced types, basically all references are passed in. This is mainly caused by the memory management of the virtual machine. The memory area in memory management generally includes heap and stack. The stack is mainly used to store simple type data used in the current call stack: string, boolean, int, float, etc. These types of memory occupy a small amount and are easy to recycle. Basically, their values are similar to the space occupied by pointers, so they can be copied directly, and it is easier for GC to perform targeted optimization.Complex advanced types tend to occupy relatively large amounts of memory and are stored in the heap. The frequency of GC recycling is relatively low and the cost is high. Therefore, passing references/pointers can avoid higher-cost operations. Copy operations, save memory, and improve program running efficiency.
Therefore, you can consider using pointers in the following situations: 1. You need to change the value of the parameter; 2. Avoid copy operations; 3. Save memory; In Golang, specifically Advanced types such as struct, slice, and map are also different. In fact, only the use of struct is a bit complicated. Slice, map, and chan can all be used directly, without considering whether they are values or pointers.Go has pointers, but no pointer arithmetic. You cannot use pointer variables to iterate through the bytes of a string. When calling functions in Go, remember that variables are passed by value.
Define a pointer ' * ' by prefixing it with type: var p * int. Now p is a pointer to an integer value. All newly defined variables are assigned the zero value of their type, and the same goes for pointers. A newly defined or pointer that does not point to anything, has the value nil. In other languages, this is often called a NULL pointer, which is nil in Go. To make the pointer point to something, you can use the address operator (&), like this:package main import "fmt" func main() { var p *int fmt.Printf("%v\n",p) //← 打印 nil var i int //← 定义一个整形变量 i p = &i //← 使得 p 指向 i, 获取 i 的地址 fmt.Printf("%v\n",p) //打印内存地址 *p = 6 fmt.Printf("%v\n",*p) //打印6 fmt.Printf("%v\n",i) //打印6 }
The above is the detailed content of Why does GOLANG still have pointers?. For more information, please follow other related articles on the PHP Chinese website!