1. 用来自定义复杂数据结构
2.struct 里面可以包含多个字段(属性),字段可以是任意类型
3.struct类型可以定义方法,注意和函数的区分
4.struct类型是值类型
5.struct类型可以嵌套
6.Go语 言没有class类型,只有struct类型
1. struct 声明:
type 标识符 struct { field1 type field2 type } //例子: type Student struct { Name string Age int Score int }
2.struct 中字段访问:和其他语言一样,使用点
例子:
var stu Student
stu.Name = “tony”
stu.Age = 18
stu.Score=20
fmt.Printf(“name=%s age=%d score=%d”, stu.Name, stu.Age, stu.Score)
package main import( "fmt" ) type Test struct { A int b int } type Student struct { Age int Name string Score int Sex string a Test //struct类型可以嵌套 t Int c *int } func testStruct () { var s Student s.Age = 18 s.Name = "tom" s.Score = 80 s.Sex = "man" s.a.A = 100 s.c = new(int) //给指针分配内存 *(s.c) = 100 //给指针对应的变量赋值 fmt.Printf("name:%s age:%d score:%d sex:%s c=%d\n", s.Name, s.Age, s.Score, s.Sex, *(s.c)) fmt.Printf("%+v\n", s) s1 := s //结构体是值类型 s1.Name = "jim" *(s1.c) = 200 //结构体内的指针还是引用类型 fmt.Printf("name:%s age:%d score:%d sex:%s c=%d\n", s.Name, s.Age, s.Score, s.Sex, *(s.c)) fmt.Printf("%+v\n", s) } func main() { testStruct() }
3.struct定义的三种形式:
a.var stu Student
b.var stu *Student = new (Student)
c.var stu *Student = &Student{}
1)其中b和c返回的都是指向结构体的指针,访问形式如下:
a. stu.Name、stu.Age和stu.Score或者 (*stu).Name、(*stu).Age等
package main import( "fmt" ) type Student struct { Score int } func testStruct () { var p3 = new(Student) (*p3).Score = 100 p4 := p3 p4.Score = 1000 //语法糖,底层会转成 (*p4).Score=1000的形式 fmt.Printf("p3=%+v\n", *p3) } func main() { testStruct() }
4.struct的内存布局:struct中的所有字段在内存是连续的,布局如下:
package main import( "fmt" ) type Point struct { x int y int } type Rect struct { p1 Point p2 Point } type RectA struct { p1 *Point p2 *Point } func main(){ var r1 Rect var r2 RectA r2.p1 = new(Point) var r3 = new(Point) var r4 = new(Point) r2.p2 = new(Point) fmt.Println(r3, r4) //r1的内存布局 fmt.Printf("p1.x addr:%p\n", &r1.p1.x) fmt.Printf("p1.y addr:%p\n", &r1.p1.y) fmt.Printf("p2.x addr:%p\n", &r1.p2.x) fmt.Printf("p2.y addr:%p\n", &r1.p2.y) fmt.Println() fmt.Println() //r2的内存布局 fmt.Printf("p1.x addr:%p\n", &(r2.p1.x)) fmt.Printf("p1.y addr:%p\n", &(r2.p1.y)) fmt.Printf("p2.x addr:%p\n", &(r2.p2.x)) fmt.Printf("p2.y addr:%p\n", &(r2.p2.y)) fmt.Printf("p1:%p\n", &r2.p1) fmt.Printf("P2:%p\n", &r2.p2) }
原文地址:https://www.cnblogs.com/domestique/p/8229021.html
时间: 2024-11-14 13:03:49