go 3.37 struct
创建时间:
阅读:
struct普通变量初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
type student struct { id int name string sex byte age int addr string }
func main() { var s1 student = student{1, "mike", 'm', 18, "bj"} fmt.Println("s1 = ", s1)
s2 := student{name: "mike", addr: "bj"} fmt.Println("s2 = ", s2) }
|
struct指针变量初始化
1 2 3 4 5 6 7 8 9
| func main() { var p1 *student = &student{1, "mike", 'm', 18, "bj"} fmt.Println("p1 = ", p1)
p2 := &student{name: "mike", addr: "bj"} fmt.Println("p2 = ", p2) }
|
结构体成员的使用:指针变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| type student struct m{ id intm name string sex byte age int addr string }
func main() { var s student var p1 *student p1 = &s p1.id = 1 (*p1).name = "mike" p1.sex = 'm' p1.age = 18 p1.addr = "bj" fmt.Println("p1 = ", p1) fmt.Println("s.id = ", s.id)
p2 := new(student) p2.id = 2 p2.name = "Penny" p2.sex = 'f' p2.age = 19 p2.addr = "bj" fmt.Println("p2 = ", p2) }
|
打印结果:
1 2 3
| p1 = &{1 mike 109 18 bj} s.id = 1 p2 = &{2 Penny 102 19 bj}
|
结构体比较和赋值
比较:
如果结构体的所有成员都是可以比较的,那么结构体也是可以比较的,
那么两个结构体将可以使用==或!=运算符进行比较,但不支持 < 或 > 。
赋值:
同类型的两个结构体变量可以相互赋值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| type student struct { id int name string sex byte age int addr string }
func main() { s1 := student{1, "mike", 'm', 18, "sz"} s2 := student{1, "mike", 'm', 18, "sz"} fmt.Println("s1 == s2", s1 == s2) fmt.Println("s1 != s2", s1 != s2)
var tmp student tmp = s2 fmt.Println("tmp = ", tmp) }
|
结构体做函数参数:值传递
值传递,形参无法改变实参
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| type student struct { id int name string sex byte age int addr string }
func test01(s student) { s.id = 666 fmt.Println("test01: s = ", s)
} func main() { s := student{1, "mike", 'm', 18, "sz"} test01(s) fmt.Println("main:s =", s) }
|
结构体做函数参数:地址传递
1 2 3 4 5 6 7 8 9 10
| func test02(s *student) { s.id = 666 fmt.Println("test02: s = ", s)
} func main() { s := student{1, "mike", 'm', 18, "sz"} test01(&s) fmt.Println("main:s =", s) }
|
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 rootid@126.com
文章标题:go 3.37 struct
本文作者:Shawn
发布时间:2019-05-31, 16:09:19
最后更新:2019-05-31, 18:57:44
原始链接:https://gitrootid.github.io/2019/05/31/golang/go-3-37-struct_/
版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。