为什么Go输入nil? [英] Why does Go have typed nil?
问题描述
为什么Go会输入 nil
?为了方便起见,它会抛出一个显式的接口构象检查.无类型的 nil
有什么问题?设计人员要解决什么类型的 nil
?
Why does Go have typed nil
? It throws an explicit interface conformation check for convenience. What's the problem of untyped nil
and what did the designers want to solve with typed nil
?
推荐答案
听起来您正在询问以下错误消息:
It sounds like you're asking about this error message:
http://play.golang.org/p/h80rmDYCTI
package main
import "fmt"
type A struct {}
type B struct {}
func (a *A) Foo() {
fmt.Println("A")
}
func (b *B) Foo() {
fmt.Println("B")
}
func main() {
n := nil
n.Foo()
}
此打印:
prog.go:17: use of untyped nil
[process exited with non-zero status]
在该示例中,程序应打印"A"还是"B"?
In that example, should the program print "A" or "B"?
您必须帮助编译器做出决定.您可以通过指定 n
的类型来做到这一点.
You have to help the compiler decide. The way you do that is by specifying the type of n
.
例如:
http://play.golang.org/p/zMxUFYgxpy
func main() {
var n *A
n.Foo()
}
打印"A".
在其他语言中,如果 n
为 nil
或等效值, n.Foo()
可能会立即崩溃.Go的语言设计师决定让您确定应该怎么做.如果在不检查 nil
的情况下访问该指针,则会得到与其他语言相同的行为.
In other languages, n.Foo()
might crash immediately if n
is nil
or its equivalent. Go's language designers decided to let you determine what should happen instead. If you access the pointer without checking for nil
, you get the same behavior as in other languages.
这篇关于为什么Go输入nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!