42

golang 基础(12)指针

 5 years ago
source link: https://studygolang.com/articles/19006?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
7FzU3y7.png!web

square-gopher.png

指针

在 go 语言中指针没有 c++ 中那么复杂,因为没有指针的运算。

什么时候用指针,也就是指针的用途

  • 可能结构相对复杂数据你不想在程序中传递数据,可以通过传递地址
  • 变量一致性

在多数语言中函数的参数传递有两种

  • 值传递
    值传递会保证没有 side effect,更改函数内的变量不会影响外面的变量
  • 引用传递
    go 语言中只有值传递一种方式
var cache Cache
func f(cache Cache)

大家都知道值传递是将变量复制一份用于函数,那么对于我们定义类型,复杂数据结构的类型作为参数传递给函数时如果也需要复制一份,其实不是浪费吗,这里 cache 对象中一个指向内存保存对象的地址 pData ,复制仅是对象的内存地址。

aqmM3a7.jpg!web

![images.png](https://upload-images.jianshu.io/upload_images/8207483-3415fe5398e30ad2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

通常都会用到交换变量值的函数 swap 这里就用学到指针来实现一下,我们要交换 a 和 b 值

func swap(a, b int){
    b, a = a, b
}

func main(){
    a, b:= 3,4
    fmt.Println(a,b)
}

这样显然是不行的。

Qz6v2qr.png!web

images.png


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK