golang的new和make主要区别如下:
- make只能用来分配及初始化类型为slice,map,chan的数据;new可以分配任意类型的数据
- new分配返回的是指针,即类型*T;make返回引用,即T;
- new分配的空间被清零,make分配后,会进行初始化。
effective go举了一个例子,见:http://golang.org/doc/effective_go.html#allocation_make
对于struct的分配和初始化,除了可以使用new外,还可以这样做: T {},例如
func TestAlloc(t *testing.T) {
type T struct {
n string
i int
f float64
fd *os.File
b []byte
s bool
}
var t1 *T
t1 = new(T)
fmt.Println(t1)
t2 := T{}
fmt.Println(t2)
t3 := T{"hello", 1, 3.1415926, nil, make([]byte, 2), true}
fmt.Println(t3)
}
值得注意的是,如果使用T{}的方式初始化变量的话:
1、与C语言不同,T{}分配的局部变量是可以返回的,且返回后该空间不会释放,例如
import "fmt"
type T struct {
i, j int
}
func a(i, j int) T {
i := T { i, j}
return i
}
func b {
t = a(1, 2)
fmt.Println(t)
}
2、一个语法问题
使用T{}来初始化时,符号}不能单独占一行,否则会报错,如下:
missing ',' before newline in composite literal
或者
syntax error: need trailing comma before newline in composite literal
non-declaration statement outside function body
syntax error: unexpected }
我曾经因为这个问题找了很久才解决。