定义结构体
type Student struct {
id int
name string
sex byte
age int
address string
}
1
2
3
4
5
6
7
实例
type Student struct {
id int
name string
sex byte
age int
address string
}
func main() {
var s1 Student = Student{1, "panghu", 'm', 18, "china"}
fmt.Println(s1)
s2 := Student{name: "panghu2", id: 2}
fmt.Println(s2)
var p1 *Student = &Student{1, "panghu", 'm', 18, "china"}
fmt.Println(*p1)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
结构体普通变量
type Student struct {
id int
name string
sex byte
age int
address string
}
func main() {
var s Student
s.id = 1
s.name = "panghu"
s.sex = 'm'
s.age = 18
s.address = "china"
fmt.Println(s)
p2 := new(Student)
p2.id = 1
p2.name = "miku"
fmt.Println(*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
结构体做函数参数(址传递)
type Student struct {
id int
name string
sex byte
age int
address string
}
func test01(s *Student) {
s.id = 111
fmt.Println(s)
}
func main() {
s := Student{1, "panghu", 'm', 18, "china"}
test01(&s)
fmt.Println(s)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
匿名字段
type Person struct {
name string
sex byte
age int
}
type Student struct {
Person
id int
address string
}
func main() {
var s1 Student = Student{Person{"panghu", 'm', 18}, 1, "china"}
fmt.Println(s1)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
非结构体匿名字段
type myAddress string
type Person struct {
name string
sex byte
age int
}
type Student struct {
Person
int
myAddress
}
func main() {
s := Student{Person{"panghu", 'm', 18}, 1, "china"}
fmt.Println(s)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
方法
type Person struct {
name string
sex byte
age int
}
func (tmp Person) PrintInfo() {
fmt.Println(tmp)
}
func main() {
p := Person{"panghu", 'm', 18}
p.PrintInfo()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
方法的继承
type Person struct {
name string
age int
}
type Student struct {
Person
address string
}
func main() {
v := Student{Person{"panghu", 18}, "china"}
fmt.Println(v)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
方法值
type Person struct {
name string
age int
}
func (p Person) GetInfo() {
fmt.Println("i am GetInfo")
}
func main() {
p := Person{"name", 18}
v := p.GetInfo
v()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15