0
点赞
收藏
分享

微信扫一扫

Go语言之参数传递

东方小不点 2024-07-24 阅读 33

文章收录在网站:http://hardyfish.top/

文章收录在网站:http://hardyfish.top/

文章收录在网站:http://hardyfish.top/

文章收录在网站:http://hardyfish.top/

在这里插入图片描述

修改参数

func main() {
   p:=person{name: "张三",age: 18}
   modifyPerson(p)
   fmt.Println("person name:",p.name,",age:",p.age)
}

func modifyPerson(p person)  {
   p.name = "李四"
   p.age = 20
}

type person struct {
   name string
   age int
}
person name: 张三 ,age: 18
modifyPerson(&p)
func modifyPerson(p *person)  {
   p.name = "李四"
   p.age = 20
}
person name: 李四 ,age: 20

值类型

func main() {
   p:=person{name: "张三",age: 18}
   fmt.Printf("main函数:p的内存地址为%p\n",&p)
   modifyPerson(p)
   fmt.Println("person name:",p.name,",age:",p.age)
}

func modifyPerson(p person)  {
   fmt.Printf("modifyPerson函数:p的内存地址为%p\n",&p)
   p.name = "李四"
   p.age = 20
}
main函数:p的内存地址为0xc0000a6020
modifyPerson函数:p的内存地址为0xc0000a6040
person name: 张三 ,age: 18
image-20240405204640653

指针类型

func main() {
   p:=person{name: "张三",age: 18}
   fmt.Printf("main函数:p的内存地址为%p\n",&p
   modifyPerson(&p)
   fmt.Println("person name:",p.name,",age:",p.age)
}

func modifyPerson(p *person)  {
   fmt.Printf("modifyPerson函数:p的内存地址为%p\n",p)
   p.name = "李四"
   p.age = 20
}
main函数:p的内存地址为0xc0000a6020
modifyPerson函数:p的内存地址为0xc0000a6020
person name: 李四 ,age: 20

引用类型

map

func main() {

   m:=make(map[string]int)

   m["飞雪无情"] = 18

   fmt.Println("飞雪无情的年龄为",m["飞雪无情"])

   modifyMap(m)

   fmt.Println("飞雪无情的年龄为",m["飞雪无情"])

}

func modifyMap(p map[string]int)  {

   p["飞雪无情"] =20

}
飞雪无情的年龄为 18

飞雪无情的年龄为 20
// makemap implements Go map creation for make(map[k]v, hint).

func makemap(t *maptype, hint int, h *hmap) *hmap{

  //省略无关代码

}
func main(){

  //省略其他没有修改的代码

  fmt.Printf("main函数:m的内存地址为%p\n",m)

}

func modifyMap(p map[string]int)  {

   fmt.Printf("modifyMap函数:p的内存地址为%p\n",p)

   //省略其他没有修改的代码

}
飞雪无情的年龄为 18

main函数:m的内存地址为0xc000060180

modifyMap函数:p的内存地址为0xc000060180

飞雪无情的年龄为 20

chan

func makechan(t *chantype, size int64) *hchan {

    //省略无关代码

}

类型的零值

举报

相关推荐

0 条评论