What does nil mean in golang?

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

What does nil mean in golang?

问题

在golang中,有许多情况下会使用nil。例如:

func (u *URL) Parse(ref string) (*URL, error) {
    refurl, err := Parse(ref)
    if err != nil {
        return nil, err
    }
    return u.ResolveReference(refurl), nil
}

但我们不能像这样使用它:

var str string //或者 var str int
str = nil

golang编译器会报错can't use nil as type string in assignment

看起来nil只能用于指向结构体和接口的指针。如果是这样的话,那么它是什么意思呢?当我们将其与其他对象进行比较时,它们是如何比较的,换句话说,golang如何确定一个对象是nil的?

编辑:例如,如果一个接口是nil,它的类型和值必须同时为nil。golang是如何实现这一点的?

英文:

There are many cases using nil in golang. For example:

func (u *URL) Parse(ref string) (*URL, error) {
	refurl, err := Parse(ref)
	if err != nil {
		return nil, err
	}
	return u.ResolveReference(refurl), nil
}

but we can't use it like this:

var str string //or var str int
str = nil

the golang compiler will throw a can't use nil as type string in assignment error.

Looks like nil can only be used for a pointer of struct and interface. If that is the case, then what does it mean?
and when we use it to compare to the other object, how do they compare, in other words, how does golang determine one object is nil?

EDIT:For example, if an interface is nil, its type and value must be nil at the same time. How does golang do this?

答案1

得分: 172

在Go语言中,nil是指针、接口、映射、切片、通道和函数类型的零值,表示一个未初始化的值。

nil并不意味着某种"未定义"的状态,它本身就是一个合法的值。在Go中,只有当对象的值为nil时,它才被认为是nil。而对象只有在属于上述类型之一时才能为nil

error是一个接口,因此nil是其有效的值,而对于string来说则不是。显而易见,nil错误表示没有错误

英文:

In Go, nil is the zero value for pointers, interfaces, maps, slices, channels and function types, representing an uninitialized value.

nil doesn't mean some "undefined" state, it's a proper value in itself. An object in Go is nil simply if and only if it's value is nil, which it can only be if it's of one of the aforementioned types.

An error is an interface, so nil is a valid value for one, unlike for a string. For obvious reasons a nil error represents no error.

答案2

得分: 9

在Go语言中,nil简单地表示其他语言中的NULL指针值。

你可以有效地将其用作任何指针或接口(接口在某种程度上也是指针)的替代。

你可以将其用作错误,因为错误类型是一个接口

你不能将其用作字符串,因为在Go语言中,字符串是一个值。

在Go语言中,nil是无类型的,这意味着你不能这样做:

var n = nil

因为这里缺少n的类型。然而,你可以这样做:

var n *Foo = nil

请注意,由于nil是指针和接口的零值,未初始化的指针和接口将是nil

英文:

nil in Go is simply the NULL pointer value of other languages.

You can effectively use it in place of any pointer or interface (interfaces are somewhat pointers).

You can use it as an error, because the error type is an interface.

You can't use it as a string because in Go, a string is a value.

nil is untyped in Go, meaning you can't do that:

var n = nil

Because here you lack a type for n. However, you can do

var n *Foo = nil

Note that nil being the zero value of pointers and interfaces, uninitialized pointers and interfaces will be nil.

答案3

得分: 4

"nil也是一个值,但唯一的区别是它是空的。

在JavaScript中,未初始化的变量将为undefined。同样,Golang对于所有未初始化的数据类型,默认值为nil。"

英文:

nil is also a value but only difference is- it is empty.

In Javascript for the un-initialized variable will be undefined. In the same way Golang has nil as default value for all the un-initalized data types.

答案4

得分: 2

在Go语言中,nil 表示指针、接口、映射、切片和通道的零值。它意味着该值未初始化。

英文:

nil in Go means a zero value for pointers, interfaces, maps, slices, and channels.
It means the value is uninitialized

答案5

得分: 1

对于像切片(slice)和指针(pointers)这样“引用”其他类型的数据类型,"nil"表示变量不引用任何实例(相当于其他语言中的空指针)。
对于函数、映射(maps)、接口(interfaces)、通道(channels)和结构体(structures)类型的变量,它们的零值就是"nil"。

英文:
  • For the data types like slice and pointers which "refer" to other types, "nil" indicates that the variable does not refer to an instance (equivalent of null pointer in other languages)
  • It is thee zero value of the variables of type functions, maps, interfaces, channels and structures

答案6

得分: 1

nil是Go语言中的一个预声明标识符,表示指针、接口、通道、映射、切片和函数类型的零值
对于指针和接口来说,nil就是它们的零值,未初始化的指针和接口将会是nil

在Go语言中,字符串不能是nil。字符串不符合被赋值为nil的条件。

a := nil   // 这会抛出一个错误 'use of untyped nil'

var a *int = nil  // 这是可以的
英文:

nil is a predeclared identifier in Go that represents zero values for pointers, interfaces, channels, maps, slices and function types.
nil being the zero value of pointers and interfaces, uninitialized pointers and interfaces will be nil.

In Go, string can’t be nil. A string doesn’t qualify to be assigned nil.

a := nil   // It will throw an error 'use of untyped nil'

var a *int = nil  //It will work

答案7

得分: 1

在Go语言中,nil是一个预声明的标识符,用于表示指针、接口、通道、映射、切片和函数类型的空值。未初始化的指针和接口将被赋值为nil。字符串不符合上述类型的任何一种,因此不能被赋值为nil

如果你使用简短声明方式声明一个变量,例如:variable:=nil,这将导致编译时错误,因为编译器无法确定要将哪种类型赋给variable

在Go语言中,映射、切片和函数不支持比较,但可以与nil进行比较。如果将任意两个映射、切片或函数赋值为nil并进行比较,将引发运行时错误。但是,如果将nil赋值给任意两个指针变量并进行比较,则不会发生错误。

以下是一个示例代码,它可以正常工作并输出equal

package main

import (
	"fmt"
)

func main() {
	var i *int = nil
	var j *int = nil
	if i == j {
		fmt.Println("equal")
	} else {
		fmt.Println("no")
	}
}

希望对你有帮助!

英文:

In Go nil is predeclared identifier that represents nothing for pointers, interfaces, channels, maps, slices and function types. Uninitialized pointers and interfaces will be nil. A string doesn’t qualify to be either of the above-mentioned types and hence can’t be assigned nil.
If you declare a variable by shorthand decleration like this: variable:=nil this will give compile time error because compiler has no idea which type it has to assign to variable .

In Go map, slice and function doesn't support comparison but can be compared with nil.
If any two map, slice or function are assigned to nil and compared with each other then it will raise runtime error.
But if we assign nil to any two pointer variables and compare them with each other then no error will occur.

package main

import (
"fmt"
)

 func main() {
    var i *int =nil
    var j *int =nil
    if i==j {
      fmt.Println("equal")
    } else {
      fmt.Println("no")
    }
}

This code works fine and prints output as equal.

答案8

得分: 0

在Golang中,可以使用nil的数据类型有指针(pointers)、接口(interfaces)、映射(maps)、切片(slices)、通道(channels)、函数类型(function types)和错误(errors)。

字符串中,值是""(空字符串)。

整数中,值是ZERO(零)。

英文:

In Golang, datatype can use nil is pointers, interfaces, maps, slices, channels, function types and errors

in String value is ""

in INT value is ZERO

答案9

得分: 0

Golang中,零值是已定义变量的默认值。不同数据类型的默认值如下:

  • 整数类型为0
  • 浮点类型为0.0
  • 布尔类型为false
  • 字符串类型为""
  • 接口、切片、通道、映射、指针和函数类型为nil

因此,nil是接口、切片、通道、映射、指针和函数的零值或默认值。

例如,

var a int
var s []int
var s1 []int = []int{1, 2}

fmt.Println(a == nil) // 报错
// invalid operation: a == nil (mismatched types int and untyped nil)

fmt.Println(s == nil) // true
fmt.Println(s1 == nil) // false

由于error是一个接口,我们可以这样写:

_, err := Parse("")
if err != nil { // 如果有错误
  // 处理错误
}
英文:

In Golang, zero value is the default value for defined variables. The default value of different datatypes are:

  • 0 for integer types
  • 0.0 for floating types
  • false for boolean types
  • "" for string types
  • nil for interfaces, slices, channels, maps, pointers and functions

So, nil is the zero value or default value for interfaces, slices, channels, maps, pointers and functions.

For example,

var a int
var s []int
var s1 []int = []int{1, 2}

fmt.Println(a == nil) // throw error
// invalid operation: a == nil (mismatched types int and untyped nil)

fmt.Println(s == nil) // true
fmt.Println(s1 == nil) // false

Since error is an interface, we can write

_, err := Parse("")
if err != nil { // if there is an error
  // handle error
}

huangapple
  • 本文由 发表于 2016年3月14日 16:56:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/35983118.html
匿名

发表评论

匿名网友

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

确定