search
HomeBackend DevelopmentGolangA brief analysis of nil and zero values ​​​​in Golang

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

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

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)

当你在 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))

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

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

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

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)

会打印:

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

在 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

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

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

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
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
How to do the security settings of LibOffice on DebianHow to do the security settings of LibOffice on DebianMay 16, 2025 pm 01:24 PM

Ensuring overall security on Debian systems is crucial to protecting the running environment of applications such as LibOffice. Here are some general recommendations for improving system security: System updates regularly update the system to patch known security vulnerabilities. Debian12.10 released security updates that fixed a large number of security vulnerabilities, including some critical software packages. User permission management avoids the use of root users for daily operations to reduce potential security risks. It is recommended to create a normal user and join the sudo group to limit direct access to the system. The SSH service security configuration uses SSH key pairs to authenticate, disable root remote login, and restrict login with empty passwords. These measures can enhance the security of SSH services and prevent

How to configure Rust compilation options on DebianHow to configure Rust compilation options on DebianMay 16, 2025 pm 01:21 PM

Adjusting Rust compilation options on Debian system can be achieved through various ways. The following is a detailed description of several methods: Use the rustup tool to configure and install rustup: If you have not installed rustup yet, you can use the following command to install: curl--proto'=https'--tlsv1.2-sSfhttps://sh.rustup.rs|sh Follow the prompts to complete the installation process. Set compilation options: rustup can be used to configure compilation options for different toolchains and targets. You can set compilation options for a specific project using the rustupoverride command. For example, if you want to set a specific Rust version for a project

How to manage Kubernetes nodes on DebianHow to manage Kubernetes nodes on DebianMay 16, 2025 pm 01:18 PM

Managing Kubernetes (K8S) nodes on a Debian system usually involves the following key steps: 1. Installing and configuring Kubernetes components preparation: Make sure that all nodes (including master nodes and worker nodes) have the Debian operating system installed and meet the basic requirements for installing a Kubernetes cluster, such as sufficient CPU, memory and disk space. Disable swap partition: In order to ensure that kubelet can run smoothly, it is recommended to disable swap partition. Set firewall rules: allow necessary ports, such as ports used by kubelet, kube-apiserver, kube-scheduler, etc. Install container

Golang's security settings on DebianGolang's security settings on DebianMay 16, 2025 pm 01:15 PM

When setting up a Golang environment on Debian, it is crucial to ensure system security. Here are some key security setup steps and suggestions to help you build a secure Golang development environment: Security setup steps System update: Make sure your system is up to date before installing Golang. Update the system package list and installed packages with the following command: sudoaptupdatesudoaptupgrade-y Firewall Configuration: Install and configure a firewall (such as iptables) to limit access to the system. Only necessary ports (such as HTTP, HTTPS, and SSH) are allowed. sudoaptininstalliptablessud

How to optimize the performance of Kubernetes deployment on DebianHow to optimize the performance of Kubernetes deployment on DebianMay 16, 2025 pm 01:12 PM

Optimizing and deploying Kubernetes cluster performance on Debian is a complex task involving multiple aspects. Here are some key optimization strategies and suggestions: Hardware resource optimization CPU: Ensure that sufficient CPU resources are allocated to Kubernetes nodes and pods. Memory: Increases the memory capacity of the node, especially for memory-intensive applications. Storage: Use high-performance SSD storage and avoid using network file systems (such as NFS) as they may introduce latency. Kernel parameter optimization edit /etc/sysctl.conf file, add or modify the following parameters: net.core.somaxconn: 65535net.ipv4.tcp_max_syn

How to schedule tasks in Debian by Python scriptsHow to schedule tasks in Debian by Python scriptsMay 16, 2025 pm 01:09 PM

In the Debian system, you can use cron to arrange timed tasks and realize the automated execution of Python scripts. First, start the terminal. Edit the crontab file of the current user by entering the following command: crontab-e If you need to edit the crontab file of other users with root permissions, please use: sudocrontab-uusername-e to replace username with the username you want to edit. In the crontab file, you can add timed tasks in the format as follows: *****/path/to/your/python-script.py These five asterisks represent minutes (0-59) and small

How to configure Golang network parameters in DebianHow to configure Golang network parameters in DebianMay 16, 2025 pm 01:06 PM

Adjusting Golang's network parameters in Debian system can be achieved in many ways. The following are several feasible methods: Method 1: Temporarily set environment variables by setting environment variables: Enter the following command in the terminal to temporarily set environment variables, and this setting is only valid in the current session. exportGODEBUG="gctrace=1netdns=go" where gctrace=1 will activate garbage collection tracking, and netdns=go will make Go use its own DNS resolver instead of the system default. Set environment variables permanently: add the above command to your shell configuration file, such as ~/.bashrc or ~/.profile

What are the shortcut keys for LibOffice on DebianWhat are the shortcut keys for LibOffice on DebianMay 16, 2025 pm 01:03 PM

The shortcut keys for customizing LibOffice on Debian systems can be adjusted through system settings. Here are some commonly used steps and methods to set LibOffice shortcut keys: Basic steps to set LibOffice shortcut keys Open system settings: In the Debian system, click the menu in the upper left corner (usually a gear icon), and select "System Settings". Select a device: In the system settings window, select "Device". Select a keyboard: On the Device Settings page, select Keyboard. Find the command to the corresponding tool: In the keyboard settings page, scroll down to the bottom to see the "Shortcut Keys" option. Clicking it will bring a window to a pop-up. Find the corresponding LibOffice worker in the pop-up window

See all articles

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 Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.