-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path31-struct.go
70 lines (56 loc) · 1.3 KB
/
31-struct.go
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package _struct
import "fmt"
type student struct {
name string
age int
}
type rectangle struct {
width int
long int
}
func main() {
var s student //普通结构体实例
var s1 *student //结构体指针
s = student{name: "snailzed", age: 24}
s1 = &student{name: "oyxp", age: 24} //指定字段初始化,未初始化的字段则为该类型的默认值
s2 := student{"oyxp1", 1} //顺序初始化
s3 := new(student) //使用new获取实例
s3 = &student{}
s3.age = 456
testStruct(s2)
fmt.Println(s, s.name, s.age)
fmt.Println(s1, s1.name, s1.age)
fmt.Println(s2, s2.name, s2.age)
fmt.Println(s3, s3.name, s3.age)
r := rectangle{width: 100, long: 100}
Area(r)
fmt.Println(FileInstance(1, "test"))
testFuncSet()
}
//普通结构体变量作为参数是值传递,指针变量为引用传递
func testStruct(s student) {
s.age = 999
s.name = "12131qweqweqw"
}
func Area(r rectangle) {
fmt.Println(r.long * r.width)
}
//名字改为小写的
type file struct {
fd int
name string
}
func FileInstance(fd int, name string) *file {
return &file{fd: fd, name: name}
}
func testFuncSet() {
s := student{name: "snail", age: 24}
s.testPointer()
s.testNormal()
}
func (s *student) testPointer() {
fmt.Println(s)
}
func (s student) testNormal() {
fmt.Println(s)
}