# [译] part 15: golang 指针 pointers

https://juejin.im/post/5ca992d7e51d452b653f8f0e

## 声明指针

* T是指针变量的类型，它指向类型为T的值。

package mainimport (      "fmt")func main() {      b := 255    var a *int = &b    fmt.Printf("Type of a is %T\n", a)    fmt.Println("address of b is", a)}

Run in playgroud

＆运算符用于获取变量的地址。上面程序的第 9 行，我们将b的地址分配给其类型为* inta。现在可以说a指向b。当我们打印a的值时就是b的地址。输出，

Type of a is *int  address of b is 0x1040a124

## 指针的零值

package mainimport (      "fmt")func main() {      a := 25    var b *int    if b == nil {        fmt.Println("b is", b)        b = &a        fmt.Println("b after initialization is", b)    }}

Run in playgroud

b在上述程序中最初为nil，然后将a的地址赋值给b。输出，

b is <nil>  b after initialisation is 0x1040a124

## 指针解引用

package main  import (      "fmt")func main() {      b := 255    a := &b    fmt.Println("address of b is", a)    fmt.Println("value of b is", *a)}

Run in playground

address of b is 0x1040a124  value of b is 255

package mainimport (      "fmt")func main() {      b := 255    a := &b    fmt.Println("address of b is", a)    fmt.Println("value of b is", *a)    *a++    fmt.Println("new value of b is", b)}

Run in playgroud

address of b is 0x1040a124  value of b is 255  new value of b is 256

## 将指针传递给函数

package mainimport (      "fmt")func change(val *int) {      *val = 55}func main() {      a := 58    fmt.Println("value of a before function call is",a)    b := &a    change(b)    fmt.Println("value of a after function call is", a)}

Run in playgroud

value of a before function call is 58  value of a after function call is 55

## 不要将指向数组的指针作为函数的参数，应该改用切片

package mainimport (      "fmt")func modify(arr *[3]int) {      (*arr)[0] = 90}func main() {      a := [3]int{89, 90, 91}    modify(&a)    fmt.Println(a)}

Run in playgroud

a [x](* a)[x]的简写。所以上面程序中的(* arr)[0]可以用arr [0]代替。让我们用这个语法重写上面的程序。

package mainimport (      "fmt")func modify(arr *[3]int) {      arr[0] = 90}func main() {      a := [3]int{89, 90, 91}    modify(&a)    fmt.Println(a)}

Run in playgroud 该程序也会输出[90 90 91]

package mainimport (      "fmt")func modify(sls []int) {      sls[0] = 90}func main() {      a := [3]int{89, 90, 91}    modify(a[:])    fmt.Println(a)}

Run in playgroud

## Go 不支持指针算数运算

Go 不支持指针算运算，这点和像 C 这样的其他语言不同。

package mainfunc main() {      b := [...]int{109, 110, 111}    p := &b    p++}

ft_authoradmin  ft_create_time2019-08-03 16:35
ft_update_time2019-08-03 16:36