Golang:值类型与引用类型

Golang is a pass by value language, so any time we pass a value to a function either as a receiver or as an argument that data is copied in memory and so the function by default is always going to be working on a copy of our data structure. We can address this problem and modify the actual underlying data structure through the use of pointers and memory address.

值类型

先来看一段代码:

package main

import (
    "fmt"
)

type person struct {
    name string
}

func (p person) print() {
    fmt.Printf("%+v", p)
}

func (p person) updateName(newName string) {
    p.name = newName
}

func main() {
    jim := person{name: "Jim"}
    jim.updateName("Jimmy")
    jim.print()
}

运行结果:

{name:Jim}

没有达到我们期待的结果:

{name:Jimmy}

值传递意味着每当我们将某个值传递给函数时,golang 就会取那个值或那个结构。
为了达到我们的预期,修改源代码:

package main

import (
    "fmt"
)

type person struct {
    name string
}

func (p person) print() {
    fmt.Printf("%+v", p)
}

func (pointerToPerson *person) updateName(newName string) {
    (*pointerToPerson).name = newName
}

func main() {
    jim := person{name: "Jim"}
    jimPointer := &jim
    jimPointer.updateName("Jimmy")
    jim.print()
}

运行结果:

{name:Jimmy}

最后一点,小的改进:

func main() {
    jim := person{name: "Jim"}
    jim.updateName("Jimmy")
    jim.print()
}

pointer shortcut, go will automatically turn your variable of type person into pointer person for you.

引用类型

先看一段代码:

package main

import "fmt"

func updateSlice(s []string) {
    s[0] = "Bye"
}

func main() {
    mySlice := []string{"Hi", "There", "how", "are", "you?"}
    updateSlice(mySlice)
    fmt.Println(mySlice)
}

运行结果:

[Bye There how are you?]

运行结果为什么是这样?


When we make the slice of string golang internally is creating two separate data structures. What we call a function and pass my slice into it, golang is still behaving as a pass by value language. Even though the slice data structure is copied it is still pointing at the original array in memory, because the slice data structure and the array data structure are two separate elements in memory.

总结

Whenever you pass an integer, float, string, or struct into a function, golang will creates a copy of each argument, and these copies are used inside of the function.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,844评论 0 23
  • 很多时候我们要添加测试设备UDID到开发者账号的Devices,如果测试设备不在我们周围,我们可以通过蒲公英链接获...
    咩咩sheep阅读 3,502评论 2 1
  • “鼻子原本是用来嗅闻各种或刺激或清淡的气息,包括柴油味儿或者紫薇花香,而不是用来托住眼镜的;耳朵原本是用来不加选择...
    踏曦行阅读 492评论 0 2
  • 文:cloud |图:花瓣 每碗泡面都有我们野蛮生长的样子 好东西不一定健康优雅,积极向上,好,更多时候是一种自我...
    72滩阅读 398评论 0 1
  • 如果说书名是一个招牌的话,那么内容就相当于店铺经营的项目和商品。招牌对店铺来说很重要,书名对读者来说同样重要。一个...
    柳二白阅读 1,067评论 0 8