Table of Contents
Non-empty and empty types
总结
Home Backend Development Golang A brief analysis of nil and zero values ​​​​in Golang

A brief analysis of nil and zero values ​​​​in Golang

Feb 07, 2023 pm 06:11 PM
golang go language nil

A brief analysis of nil and zero values ​​​​in Golang

As a long-time Java developer, I am obsessed with null checking and handling null values. In golang, the story is a little different. In this post, I will try to describe how to use nil and zero value in golang.

Non-empty and empty types


Types in go can be empty or non-empty. A non-null type can never be nil, and will never cause you to cause a nil-panic (equivalent to Java's nullpointerexception) Although not as much as in java (or other languages ​​with null types) We still have to be a little cautious when dealing with empty types.

Non-null basic types

In go, basic types cannot be null. A declaration like

var a int = nil
Copy after login

fails to compile because int can never be nil. The default value of an unallocated int type is 0.
Run Statement

var a int // int类型的默认值不能为nil
fmt.Println(a) // 0
Copy after login

will output the default value of int "0". We call this the zero value of the type.

Same as intThe default is 0, the following are other basic types whose default value is zero:

##uint, uint8, uint16, uint32, uint640uintptr0float32, float640.0byte0rune0string "" (empty string)##complex64, complex128 arrays of non-nillable typesarrays of nillable types

Non-nillable structs

组合的struct类型也是不可空的,并且struct的默认值将包含其所有字段的默认值。

设定一个 Person 结构体的代码,

type Person struct {
    Name string
    Age  int
}
var p Person // person 类型的默认 0 值

fmt.Printf("[%#v]\n", p)
Copy after login

当你在 main 方法里运行这段代码的时候,将会打印出 [main.Person{Name:"", Age:0}]  你可以在 Go Playground 上运行这段代码进行测试。

nillable 类型

还有一种更高级到 nillable 类型,如果对应的类型未初始化,将会报错,触发 panic 。

这些可以为 nillabel 类型的 函数,通道,切片,map,接口以及指针.

但是,nil-slice 和nil-maps 仍然可以使用,在我们开始使用它们之前不必进行初始化。

nil-maps

如果 map 的值为 nil,map 将始终返回值的零值,与返回不存在 map 中的 Key 的结果一样。代码

var p map[int]string // nil map
fmt.Printf(" %#v  length %d \n",  p[99], len(p))
Copy after login

让我们来打印下 "" length 0, 我们可以获得键为99的字符串string的值为零.

将值分配给 nil-map, 会引起死机状况的出现:

var p map[string]int    // nil map 
p["nils"] = 19 // panic: 对nil-map中的条目赋值
Copy after login

nil-slices

在外部引用切片 will 将导致死机,但是 len() 和 cap() 的操作不会导致死机出现. 他们只返回 0, 因为对于未初始化的切片,其容量和长度都为零. 所以他们可以在nil-slice上成功调用append. 示例代码如下:

var p []string // nil slice
fmt.Printf("uninitialized -> %d, %d\n",  len(p), cap(p))
p1 := append(p, "nils") // 从P创建一个新的切片p1
fmt.Printf("after append  -> %d, %d %#v\n",  len(p1), cap(p1), p1)
Copy after login

会打印:

uninitialized -> 0, 0
after append  -> 1, 1 []string{"nils"}
Copy after login

在 Go Playground 上试验。

可为 nil 值的指针、函数和接口类型会引起 panic

Pointers and interface-types are however nillable. Whenever dealing with these types, we have to consider if they are nil or not to avoid panics. These code-snippets for instance, will cause a panic:

指针和接口类型是可为 nil 值的。每当处理这些类型时,我们都必须考虑它们是否为零,以免出现 Panic。例如,这些代码片段将引起 Panic:

var p *int // 指向 int 的指针
*p++ // panic: runtime error: invalid memory address or nil pointer dereference
//  p是无内容的地址,因此为nil
Copy after login

var p error // 类型 error 的 nil 值
error.Error() // panic: runtime error: invalid memory address or nil pointer dereference
Copy after login

var f func(string) // nil 函数
f("oh oh") // panic: runtime error: invalid memory address or nil pointer dereference
Copy after login

nil channel 永远阻塞

尝试从 nil 通道读取或写入 nil 通道将永远受阻。关闭nil通道会引起  Panic 。

总结


nil 在go中有很好的定义。知道什么可以是 nil 以及如何处理不同类型的 nil 值可以增加您对发生的事情的理解,并且可以帮助您编写更好的 go 代码。

原文地址:https://nilsmagnus.github.io/post/nillability-in-go/

译文地址:https://learnku.com/go/t/46496

【相关推荐:Go视频教程编程教学

Types Zero value
int, int8, int16, int32, int64 0
(0,0i)
array of zero-values
array of nil-values

The above is the detailed content of A brief analysis of nil and zero values ​​​​in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? Apr 02, 2025 pm 05:03 PM

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

Do I need to install an Oracle client when connecting to an Oracle database using Go? Do I need to install an Oracle client when connecting to an Oracle database using Go? Apr 02, 2025 pm 03:48 PM

Do I need to install an Oracle client when connecting to an Oracle database using Go? When developing in Go, connecting to Oracle databases is a common requirement...

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

See all articles