golang中的函数参数值传递和引用传递

栏目: Go · 发布时间: 6年前

内容简介:在golang中函数的参数默认为如果想要使用引用传递,需要将传入的参数设置为如果传入的参数数据很大,建议使用指针类型,减少内存因拷贝参数而占用。

在golang中函数的参数默认为 按值传递 ,即在函数内部修改传入参数的值是函数外部传入值的 拷贝

如果想要使用引用传递,需要将传入的参数设置为 指针类型

如果传入的参数数据很大,建议使用指针类型,减少内存因拷贝参数而占用。

type person struct{
	Name string
	Age int
}

func SetName(p person, name string){
	p.Name = name
}

func SetNameByPointer(p *person, name string){
	p.Name = name
}

func(p person) SetPersonName(name string){
	p.Name = name
}

func(p *person) SetPersonNameByPointer(name string){
	p.Name = name
}

func main(){
	p := new(person)
	p.Name = "Tom"
	p.Age = 12
	fmt.Println(p)		// &{Tom 12}

	SetName(*p, "Jerry")
	fmt.Println(p)		// &{Tom 12}

	SetNameByPointer(p, "Jerry")
	fmt.Println(p)		// &{Jerry 12}

	p.SetPersonName("Tom")
	fmt.Println(p)		// &{Jerry 12}

	p.SetPersonNameByPointer("Tom")
	fmt.Println(p)		// &{Tom 12}
}

如果有什么问题,欢迎留言讨论,谢谢。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Advanced Web Metrics with Google Analytics

Advanced Web Metrics with Google Analytics

Brian Clifton / Sybex / 2008 / USD 39.99

Are you getting the most out of your website? Google insider and web metrics expert Brian Clifton reveals the information you need to get a true picture of your site's impact and stay competitive usin......一起来看看 《Advanced Web Metrics with Google Analytics》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具