乐闻世界logo
搜索文章和话题

What is the difference between nil and null in Go?

1个答案

1

In Go, nil is a predefined identifier representing the zero value for pointers, channels, functions, interfaces, maps, or slices. On the other hand, null does not exist in Go; it is a keyword used in other languages like Java and JavaScript to represent null references.

Examples:

In Go, when you declare a pointer variable without allocating any memory, its value is nil. For example:

go
var p *int fmt.Println(p == nil) // Output: true

In this example, p is a pointer to an integer, initially not pointing to any memory address, so its value is nil.

Similarly, if you declare a slice without initializing it, its value is also nil:

go
var s []int fmt.Println(s == nil) // Output: true

This means the slice s has not been allocated space and is empty.

In other programming languages, such as JavaScript, null is used to represent a reference to no object. For example, in JavaScript:

javascript
var obj = null; console.log(obj === null); // Output: true

Here, null is used to indicate that the variable obj currently does not point to any object.

In summary, in Go, nil should be used to represent the zero value for unallocated or uninitialized composite types and pointers, while the concept of null does not exist in Go; it is a keyword used in other languages for similar purposes.

2024年8月7日 18:15 回复

你的答案