What the difference between (*T)(nil) and &T{}/new(T)? Golang

huangapple go评论92阅读模式
英文:

What the difference between (*T)(nil) and &T{}/new(T)? Golang

问题

这两种表示法之间的微妙区别是什么?(*T)(nil)/new(T)&T{}

type Struct struct {
    Field int
}

func main() {
    test1 := &Struct{}
    test2 := new(Struct)
    test3 := (*Struct)(nil)
    fmt.Printf("%#v, %#v, %#v \n", test1, test2, test3)
    //&main.Struct{Field:0}, &main.Struct{Field:0}, (*main.Struct)(nil) 
}

似乎这个(*T)(nil)与其他表示法的唯一区别是它返回空指针或无指针,但仍为结构体的所有字段分配内存。

英文:

Could anybody explain what the subtle difference between these two notations: (*T)(nil)/new(T) and &T{}.

type Struct struct {
	Field int
}

func main() {
    test1 := &Struct{}
    test2 := new(Struct)
    test3 := (*Struct)(nil)
    fmt.Printf("%#v, %#v, %#v \n", test1, test2, test3)
    //&main.Struct{Field:0}, &main.Struct{Field:0}, (*main.Struct)(nil) 
}

Seems like the only difference of this one (*T)(nil) from other is that it returns nil pointer or no pointer, but still allocates memory for all fields of the Struct.

答案1

得分: 13

两种形式new(T)&T{}是完全等价的:它们都分配了一个零值的T并返回指向该分配内存的指针。唯一的区别是,&T{}不能用于内置类型如int;你只能使用new(int)

形式(*T)(nil)并不分配一个T,它只是返回一个空指针nil指向T。你的test3 := (*Struct)(nil)只是对惯用的var test3 *Struct的一个混淆变体。

英文:

The two forms new(T) and &T{} are completely equivalent: Both allocate a zero T and return a pointer to this allocated memory. The only difference is, that &T{} doesn't work for builtin types like int; you can only do new(int).

The form (*T)(nil) does not allocate a T it just returns a nil pointer to T. Your test3 := (*Struct)(nil) is just a obfuscated variant of the idiomatic var test3 *Struct.

huangapple
  • 本文由 发表于 2015年1月8日 04:14:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/27827871.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定