学习golang(day 6)- 指针、结构体 2022-05-20 17:06:00 编程 golang 暂无评论 250 次阅读 1261字 修改时间:2022-05-21 14:08:43 #指针 go语言中,函数传递都是值拷贝,指针就是一个变量,保存的是内存地址 golang的指针很简单,只有两个符号&(取地址) 和*(根据地址取值) **举个栗子** ```go i := 1 // 取i的地址赋值给一个指针变量 s s := &i // 0xc000014088 // 通过 * 获取指针s所对应的值 newI := *s // 1 ``` ------------ #结构体 go语言中没有类的定义,没有继承关系,没有面向对象的概念,结构体可以实现面向对象的一些特征 **定义和初始化** ```go type Dog struct { name, color string age int } // 结构体可以嵌套 type Person struct { dog Dog name string age int } func main() { // 初始化 wangchai := Dog{ name: "旺柴", color: "白色", age: 1, } tom := Person{ dog: wangchai, name: "李四", age: 19, } fmt.Printf("Person: %v\n", tom) // Person: {{旺柴 白色 1} 李四 19} // 单独设置属性 tom.name = "张三" fmt.Printf("Person: %v\n", tom) // Person: {{旺柴 白色 1} 张三 19} } ``` 匿名结构体 ```go // 直接用var声明一个结构体,对象名tom var tom struct { name string age int } func main() { tom.name = "张三" tom.age = 18 fmt.Printf("Person: %v\n", tom) } ``` **指针结构** ```go type Person struct { name string age int } // 接收一个指针 func updatePerson(p *Person) { p.name = "张三" p.age = 18 } func main() { tom := Person{ "tom", 18, } fmt.Printf("tom: %v\n", tom) // 传递tom的指针 updatePerson(&tom) fmt.Printf("tom: %v\n", tom) } ``` 标签: golang
评论已关闭