警告
本文最后更新于 2020-05-19,文中内容可能已过时。
- &T{}
- &someLocalVar
- new
- make
1
2
3
4
5
6
7
8
9
10
11
12
13
|
func main() {
p1 := new(Point)
p2 := &Point{}
p3 := &Point{2, 3}
fmt.Println(p1, p2, p3) // &{0 0} &{0 0} &{2 3}
x := new(int)
fmt.Println(x, *x) // 0xc00001e158 0
p := new(chan int) // p has type: *chan int
c := make(chan int) // c has type: chan int
fmt.Printf("%T, %T\n", p, c) // *chan int, chan int
}
|
The *
would be mandatory, so:
1
2
3
4
5
6
7
|
new(int) --> NEW(*int)
new(Point) --> NEW(*Point)
new(chan int) --> NEW(*chan int)
make([]int, 10) --> NEW([]int, 10)
// 非法操作
make(Point) // Illegal
make(int) // Illegal
|
是的,可以将new和make合并到一个内置函数中。然而,一个内置函数很可能比两个内置函数更容易让Go新手感到困惑。
考虑到以上几点,new和make保持分离似乎更合适。
Why would I make() or new()?