new(Point)
&Point{} // OK
&Point{2, 3} // Combines allocation and initialization
new(int)
&int // Illegal
// Works, but it is less convenient to write than new(int)
var i int
&i
new和make之间的区别可以通过下面的例子看出:
p := new(chan int) // p has type: *chan int
c := make(chan int) // c has type: chan int
假设Go没有new和make,但它有内置函数NEW。然后示例代码看起来像这样:
p := NEW(*chan int) // * is mandatory
c := NEW(chan int)
p *[]int = new([]int) // *p = nil, which makes p useless
v []int = make([]int, 100) // creates v structure that has pointer to an array, length field, and capacity field. So, v is immediately usable
var p *[]int = new([]int)
or
// *p == nil; with len and cap 0
p := new([]int)
这很少有用。
p := make([]int, 0)
我们的切片已经初始化,但这里指向一个空数组。
这两种说法都不是很有用,下面是:
var v []int = make([]int, 10, 50)
// Or
v := make([]int, 10, 50)
这将分配一个50个整型数组,然后创建一个长度为10,容量为50的切片v,指向数组的前10个元素。
找出make()和new()的一些规则:
对于切片、映射和通道:使用make
对于数组、结构和所有值类型:使用new
package main
type Foo map[string]string
type Bar struct {
s string
i int
}
func main() {
// OK:
y := new(Bar)
(*y).s = "hello"
(*y).i = 1
// NOT OK:
z := make(Bar) // compile error: cannot make type Bar
z.s = "hello"
z.i = 1
// OK:
x := make(Foo)
x["x"] = "goodbye"
x["y"] = "world"
// NOT OK:
u := new(Foo)
(*u)["x"] = "goodbye" // !!panic!!: runtime error:
// assignment to entry in nil map
(*u)["y"] = "world"
}
渠道:
func main() {
// OK:
ch := make(chan string)
go sendData(ch)
go getData(ch)
time.Sleep(1e9)
// NOT OK:
ch := new(chan string)
go sendData(ch) // cannot use ch (variable of type *chan string)
// as chan string value in argument to sendData
go getData(ch)
time.Sleep(1e9)
}
func sendData(ch chan string) {
ch <- "Washington"
ch <- "Tripoli"
ch <- "London"
ch <- "Beijing"
ch <- "Tokio"
}
func getData(ch chan string) {
var input string
for {
input = <-ch
fmt.Printf("%s ", input)
}
}