Pointers in Golang-Pointer

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The native data types of Go can be divided into basic types and advanced types, the basic types mainly include string, bool, int and float series, the advanced type contains Struct,array/slice,map,chan, Func.

Compared to the language of reference types such as Java,python,javascript, Golang has a relatively ancient character like the C-language pointer. But unlike the C language, Golang pointers are separate types, not int types in C, and you cannot do integer arithmetic on pointers. From this point of view, the Golang pointer is basically a kind of reference.

So why do Golang need pointers? What are the unique uses of such pointers?

When learning the reference type language, it is always first to understand that when a function/method is passed to the parameter, the value or reference is passed in. In fact, in most of the reference languages, when the argument is the basic type, it is the value that is passed in, that is, another copy of the parameter to the current function call stack. When a parameter is a high-level type, the basic of the pass-in is a reference. This is mainly due to the memory management of the virtual machine.

Memory areas in memory management typically include heap and stack, which are used primarily to store the simple type of data used by the current call stack: String,boolean,int,float, and so on. These types of memory consumption is small, easy to recycle, basically their values and pointers occupy the same space, so can be copied directly, GC is also easier to do targeted optimization. Complex advanced types occupy a relatively large amount of memory, stored in the heap, GC recovery frequency is relatively low, the cost is also large, so the reference/pointer can avoid costly replication operations, and save memory, improve the efficiency of program operation.

Therefore, you can consider using pointers in the following situations: 1, you need to change the value of the parameter, 2, avoid the copy operation; 3, save memory;

In Golang, specific to the advanced type Struct,slice,map, there are also different. In fact, only the use of structs is a bit complex, Slice,map,chan can be used directly, regardless of whether it is a value or a pointer.

struct

For functions, specified by the parameter type of the function, the type of the passed-in parameter is incorrect, for example:

Func Passvalue (s struct) {} func Passpointer (s *struct) {}

For methods, the receiver (receiver) can be a pointer or a value, and Golang is automatically adapted to match the type of the parameter before passing the parameter. That is: if the parameter of the method is a value, then according to the method of passing the value, the internal change of the struct cannot be used on the external variable, for example:

Package main import "FMT" type mypoint struct {X int Y int} func printfuncvalue (P mypoint) {p.x = 1 p.y = 1 Fmt. Printf ("-%v", p)} func printfuncpointer (pp *mypoint) {pp. X = 1//should actually be written (*PP). X,golang gave the grammatical sugar, reducing the trouble, but also led to inconsistent pp. Y = 1 FMT. Printf ("-%v", pp)} func (P mypoint) Printmethodvalue () {p.x + = 1 p.y + 1 FMT. Printf ("-%v", p)}//recommends using pointers as the recipient of the Method (Method:printmethodpointer) (Receiver:*mypoint), one can modify the recipient's value, The second is to avoid the large object copy func (pp *mypoint) printmethodpointer () {pp. X + = 1 pp. Y + = 1 fmt. Printf ("-%v", pp)} func main () {p: = mypoint{0, 0} pp: = &mypoint{0, 0} fmt. Printf ("\ n value to func (value):%v", p) printfuncvalue (p) fmt. Printf ("--%v", p)//Output:value to Func (value): {0 0}, {1 1}--{0 0}//printfuncvalue (PP)/Can Not use PP (type *mypoint) as type mypoint in argument to Printfuncvalue//printfuncpointer (p)//cannot use P (type M Ypoint) as type *mypoint in argument to PRintfuncpointer FMT. Printf ("\ n pointer to func (pointer):%v", pp) printfuncpointer (PP) fmt. Printf ("--%v", pp)//Output:pointer to Func (pointer): &{0 0}, &{1 1}--&{1 1} fmt. Printf ("\ n value to method (value):%v", p) p.printmethodvalue () fmt. Printf ("--%v", p)//Output:value to Method (value): {0 0}, {1 1} and {0 0} fmt. Printf ("\ n value to method (pointer):%v", p) p.printmethodpointer () fmt. Printf ("--%v", p)//Output:value to Method (pointer): {0 0}, &{1 1}--and {1 1} fmt. Printf ("\ n pointer to method (value):%v", pp) Pp.printmethodvalue () fmt. Printf ("--%v", pp)//Output:pointer to Method (value): &{1 1}, {2 2} and &{1 1} fmt. Printf ("\ n pointer to method (pointer):%v", pp) Pp.printmethodpointer () fmt. Printf ("--%v", pp)//Output:pointer to Method (pointer): &{1 1}, &{2 2}--&{2 2}}

Slice:

Slice is actually a reference to the array it is attached to, which does not store the data, but simply describes the array. Therefore, modifying the elements in the slice will be reflected on the array and, of course, on all slice of the array.

You can use make ([]int) to create and initialize a map.

Map:

Using make (map[string]string) returns itself as a reference and can be used directly to manipulate:

map["name"]= "Jason";

If you use a pointer to map, it will produce an error:

*map["name"]= "Jason"  //  Invalid indirect of m["title" (Type String) (*map) ["Name"]= "Jason"  //invalid Indirect of M (type map[string]string)

Chan:

Make (chan int) returns a channel that can be used directly.

Func:

In Golang, Func can be returned as a value, so a Python-like decorator can also be used to process functions.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.