Latest web development tutorials

Go language pointer

Go pointer language is easy to learn, use the Go language pointer can more easily perform some tasks.

Let us step by step to learn the language Go pointer.

We all know that the variable is a convenient placeholder for reference computer memory addresses.

Go fetch address language character is &, into a variable before using it will return the corresponding variable memory address.

The following example demonstrates the variable address in memory:

package main

import "fmt"

func main() {
   var a int = 10   

   fmt.Printf("变量的地址: %x\n", &a  )
}

Execute the above code output results:

变量的地址: 20818a220

Now that we understand what a memory address and how to access it. Next, we will introduce pointer.


What is a pointer

A pointer can point to any variable value memory address it points to the value of the memory address.

Like variables and constants, before using the pointer you need to declare a pointer. Pointer declaration in the following format:

var var_name *var-type

var-type pointer type, var_name is a pointer variable name, an asterisk is used to specify the variable as a pointer. The following is a valid pointer declaration:

var ip *int        /* 指向整型*/
var fp *float32    /* 指向浮点型 */

In this case it is a pointer to int and float32 pointer.


How to use the pointer

Pointers process:

  • Define a pointer variable.
  • Pointer variable.
  • The value of the address pointer variable access point.

In front of the pointer type add an asterisk (prefix) to obtain a pointer points to.

package main

import "fmt"

func main() {
   var a int= 20   /* 声明实际变量 */
   var ip *int        /* 声明指针变量 */

   ip = &a  /* 指针变量的存储地址 */

   fmt.Printf("a 变量的地址是: %x\n", &a  )

   /* 指针变量的存储地址 */
   fmt.Printf("ip 变量的存储地址: %x\n", ip )

   /* 使用指针访问值 */
   fmt.Printf("*ip 变量的值: %d\n", *ip )
}

Examples of the implementation of the above output is:

a 变量的地址是: 20818a220
ip 变量的存储地址: 20818a220
*ip 变量的值: 20

Go null pointer

When after a pointer is defined not assigned to any variable, its value is nil.

nil pointer is also called a null pointer.

null nil in concept and other languages, None, nil, NULL, like all refer to zero or blank values.

A pointer variable is commonly abbreviated ptr.

See the following examples:

package main

import "fmt"

func main() {
   var  ptr *int

   fmt.Printf("ptr 的值为 : %x\n", ptr  )
}

The above example output is:

ptr 的值为 : 0

Null pointer judgment:

if(ptr != nil)     /* ptr 不是空指针 */
if(ptr == nil)    /* ptr 是空指针 */

Go pointer More

Next, we will introduce more languages ​​Go pointers applications:

content description
Go pointer array You can define a pointer array to store address
Go pointer to a pointer Go support pointer to a pointer
Go like a function pointer parameters passed By reference or address the Senate, when the function call can change its value