在Go语言中,如何表示“null”值?

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

How do you express a "null" value in Go?

问题

在Go语言中,如何表示一个"null"值?

type Node struct { 
	next *Node
	data interface{}
}

我想要表达的是

return &Node{ data: nil, next: nil }
英文:

How do you express a "null" value in Go?

type Node struct { 
	next *Node
	data interface{}
}

And I want to say

return &Node{ data: NULL, next: NULL }

答案1

得分: 141

NULL的等价物是nil,正如你已经发现的那样。但是请注意,通常在Go语言中不需要将变量初始化为nil或零,因为默认情况下,所有变量(包括动态分配的变量)都会根据类型设置为“零值”(数字为零,引用为nil)。因此,在你的例子中,使用new(Node)会得到一个两个字段都为nil的Node。

英文:

The equivalent of NULL is nil, as you already discovered. Note, though, that you don't generally need to initialize things to nil or zero in Go, because by default all variables (including dynamically allocated ones) are set to “zero values” according to type (numbers zero, references nil). So in your example saying new(Node) would result in a Node with both fields nil.

答案2

得分: 25

我刚刚发现是nil

英文:

I just found out is nil

huangapple
  • 本文由 发表于 2010年11月19日 01:44:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/4217864.html
匿名

发表评论

匿名网友

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

确定