教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Go 类型的零值

Go 类型的零值

发布时间:2022-03-05   编辑:jiaochengji.com
教程集为您提供Go 类型的零值等资源,欢迎您收藏本站,我们将为您提供最新的Go 类型的零值资源
<h1>本文视频地址</h1><h1>1. Go 类型的零值</h1>

当通过声明或调用new为变量分配存储空间,或者通过复合文字字面量或make调用创建新值,
并且还不提供显式初始化的情况下,Go会为变量或值提供默认值。

Go 语言的每种原生类型都有其默认值,这个默认值就是这个类型的零值。内置零值如下:

所有整型类型:0
浮点类型:0.0
布尔类型:false
字符串类型:""
指针、interface、slice、channel、map、function:nil

数组、结构体等类型的零值初始化就是对其组成元素逐一进行零值初始化。

<h1>2. 零值可用</h1>

例子1:

<pre><code class="lang-go"> var foods []int foods = append(foods, 1) foods = append(foods, 2) fmt.Println(foods) // 输出:[1 2]</code></pre>

如上,声明了一个 []int 类型的 slice:foods,我们并没有对其进行显式初始化,这样 foods 这个变量被 Go 编译器置为零值:nil。在Go语言中零值是可用的,我们可以直接对其使用 append 操作,并且不会出现引用 nil 的错误。

例子2: 通过 nil 指针调用方法

<pre><code class="lang-go"> type Person struct {} func main() { var p *Person fmt.Println(p) //输出:<nil> }</code></pre>

我们声明了一个 Person 的指针变量,我们并未对其显式初始化,指针变量 p 会被 Go 编译器赋值为 nil。

在 Go 标准库和运行时代码中,典型的零值可用:sync.Mutex 和 bytes.Buffer

<pre><code class="lang-go">var mu sync.Mutex mu.Lock() mu.Unlock() var b bytes.Buffer b.Write([]byte(“Hello Golang")) fmt.Println(b.String()) // 输出:Hello Golang</code></pre>

我们看到我们无需对 bytes.Buffer 类型的变量 b 进行任何显式初始化即可直接通过 b 调用其方法进行写入操作,这源于 bytes.Buffer 底层存储数据的是同样支持零值可用策略的 slice 类型:

<pre><code class="lang-go">// $GOROOT/src/bytes/buffer.go // A Buffer is a variable-sized buffer of bytes with Read and Write methods. // The zero value for Buffer is an empty buffer ready to use. type Buffer struct { buf []byte // contents are the bytes buf[off : len(buf)] off int // read at &buf[off], write at &buf[len(buf)] lastRead readOp // last read operation, so that Unread* can work correctly. }</code></pre>

另外,非所有类型都是零值可用的:

<pre><code class="lang-go">var nums []int nums[0] = 66 // 报错! nums = append(nums, 66) // OK var m map[string]int m["price"] = 1 // 报错! m1 := make(map[string]int m1["price"] = 1 // OK var m sync.Mutex mu1 := m // Error: 避免值拷贝 foo(m) // Error: 避免值拷贝</code></pre>

您可能感兴趣的文章:
Go 类型的零值
从零学习 Go 语言(33):如何手动实现一个协程池?
编程书说的“Go程序员应该让聚合类型的零值也具有意义”是在讲什么
Golang中make与new有何区别?
从零学习 Go 语言(12):流程控制之defer 延迟语句
从零学习 Go 语言(24):理解 Go 语言中的 goroutine
Go语言-零基础入门视频教程
golang 类型_什么是Golang类型
golang 基础知识点
什么是Golang类型

上一篇:08.无类型常量 下一篇:12.Go字符串
[关闭]
~ ~