Hexo

凡事预则立,不预则废


  • Home

  • Tags

  • Archives

  • Navigation

  • Search

Go语言——struct类型作为函数参数

本文先给出Go语言中struct类型作为函数参数传入的例子,然后给出总结


首先看下面代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func changeValue(person Person){
person.name = "sanye"
person.age = 22
}

func changePoint(person *Person){
person.name = "sanye"
person.age = 22
}
func main() {
person := Person{
name:"origin",
}
changeValue(person)
fmt.Printf("Person:\n person.name: %s---person.age: %d\n", person.name, person.age)
changePoint(&person)
fmt.Printf("*Person:\n person.name: %s---person.age: %d\n", person.name, person.age)
}

//output:
//Person:
// person.name: origin---person.age: 0
//*Person:
// person.name: sanye---person.age: 22

总结

  • struct类型的传递是按值传递的,与数组[5]byte等的传递相似,也可以理解为和C++一样
  • struct类型传递与切片不同,切片事实上是一个指针(栈)指向一块数组(堆)这样的数据结构,所以无论如何都是传入指针或者是指针(栈)的指针(指向栈)
  • 可以理解为: 切片类似于Java(切片还多了个特色,通过传入切片可以修改指针(栈)本身,而Java是做不到的), 而数组类似于C++

注意:struct类型与切片传值方式不同而与数组相同

Hello World

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server

Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment

1…295296297…352
San Ye

San Ye

Stay Hungry. Stay Foolish.

704 posts
53 tags
© 2026 San Ye
Powered by Hexo
|
Theme — NexT.Gemini v5.1.4