-
Notifications
You must be signed in to change notification settings - Fork 0
/
new_make.go
46 lines (36 loc) · 1020 Bytes
/
new_make.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
package main
import (
"./pack1"
"fmt"
)
type Foo map[string]string
type Bar struct {
thingOne string
thingTwo int
}
func main() {
// OK
// 试图 make() 一个结构体变量,会引发一个编译错误,这还不是太糟糕,但是 new() 一个 map 并试图向其填充数据,将会引发运行时错误!
// 因为 new(Foo) 返回的是一个指向 nil 的指针,它尚未被分配内存。所以在使用 map 时要特别谨慎
y := new(Bar)
(*y).thingOne = "hello"
(*y).thingTwo = 1
// NOT OK
//z := make(Bar) // 编译错误:cannot make type Bar
//(*z).thingOne = "hello"
//(*z).thingTwo = 1
// OK
x := make(Foo)
x["x"] = "goodbye"
x["y"] = "world"
// NOT OK
//u := new(Foo)
//(*u)["x"] = "goodbye" // 运行时错误!! panic: assignment to entry in nil map
//(*u)["y"] = "world"
//struct1 := new(structPack.ExpStruct)
struct1 := new(pack1.ExpStruct)
struct1.Mi1 = 10
struct1.Mf1 = 16.
fmt.Printf("Mi1 = %d\n", struct1.Mi1)
fmt.Printf("Mf1 = %f\n", struct1.Mf1)
}