他們不僅給出相同的結果值,但如果我們的東西分配兩種方式,看看自己的價值觀......
// Adapted from http://tour.golang.org/#30
package main
import "fmt"
type Vertex struct {
X, Y int
}
func main() {
v := &Vertex{}
v2 := new(Vertex)
fmt.Printf("%p %p", v, v2)
}
...我們會發現它們實際上分配在連續的內存插槽中。典型輸出:0x10328100 0x10328108
。我不確定這是實現細節還是規範的一部分,但它確實表明它們都是從同一個池中分配的。
Play around with the code here.
至於新的初始化,根據the language spec:The built-in function new takes a type T and returns a value of type *T. The memory [pointed to] is initialized as described in the section on initial values.
因爲去功能不能超載,這是不是一個可變參數函數,有沒有辦法在任何初始化數據傳遞。相反,如果適當,那麼去任何版本的0
都可以對該類型和任何成員字段進行初始化。
有沒有一種方法來初始化使用新的字段? – allyourcode
@allyourcode不這麼認爲。 http://stackoverflow.com/questions/4498998/how-to-initialize-members-in-go-struct – Woot4Moo
那麼文檔會說,他們爲什麼選擇包含'new'函數?我認爲'go'是所有關於非重疊功能的。 –