13

They seem to be the same:

package main

import "fmt"

type S struct {
    i int
}

func main() {
  var s1 *S = new(S)
  fmt.Println(s1)

  var s2 *S = &S{}
  fmt.Println(s2)  // Prints the same thing.
}

Update:

Hm. I just realized that there's no obvious way to initialize S.i using new. Is there a way to do that? new(S{i:1}) does not seem to work :/

4

3 回答 3

12

有效的开始:

作为一种限制情况,如果复合文字根本不包含任何字段,它会为该类型创建一个零值。表达式new(File)&File{}是等价的。

于 2013-08-24T16:25:42.523 回答
1

它们不仅给出相同的结果值,而且如果我们以两种方式分配一些东西并查看它们的值......

// 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. 我不确定这是实现细节还是规范的一部分,但它确实表明它们都是从同一个池中分配的。

在这里玩代码。

至于用new初始化,根据语言规范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.因为go中的函数不能重载,而且这不是可变参数函数,所以没有办法传入任何初始化数据。相反,go 将根据需要使用0对类型和任何成员字段有意义的任何版本对其进行初始化。

于 2014-08-13T23:35:43.117 回答
0
Case 1: package main

import (
    "fmt"
)

type Drink struct {
    Name    string
    Flavour string
}

func main() {
    a := new(Drink)
    a.Name = "Maaza"
    a.Flavour = "Mango"
    b := a
    fmt.Println(&a)
    fmt.Println(&b)
    b.Name = "Frooti"

    fmt.Println(a.Name)

}//This will output Frooti for a.Name, even though the addresses for a and b are different.

Case 2:
package main

import (
    "fmt"
)

type Drink struct {
    Name    string
    Flavour string
}

func main() {
    a := Drink{
        Name:    "Maaza",
        Flavour: "Mango",
    }

    b := a
    fmt.Println(&a)
    fmt.Println(&b)
    b.Name = "Froti"

    fmt.Println(a.Name)

}//This will output Maaza for a.Name. To get Frooti in this case assign b:=&a.
于 2018-06-03T07:37:43.037 回答