99
Go语言笔记 | 05-变量零值
source link: https://studygolang.com/articles/18103?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
当一个变量被声明之后, 如果没有初始化, 系统自动赋予它该类型的零值
零值初始化机制可以确保每个声明的变量总是有一个良好定义的值
基本类型的零值
几种基本类型的零值
false 0 0.0 空字符串 ""
package main import "fmt" var ( str string // "" avg, sum float32 // 0.0, 0.0 ) func main() { var ( b bool i int f float32 str string ) fmt.Println(b, i, f, str) // false 0 0 }
引用类型的零值
引用类型的零值为 nil
, 常见的引用类型有: point
, function
, interface
, slice
, channel
, map
package main import ( "fmt" ) func main() { var ( i *int // 指针 pointer f func() // 函数 function a interface{} // 接口 interface b []string // 切片 slice c chan int // 通道 channel m map[int]string // map ) fmt.Println(i, f, a, b, c, m) // <nil> <nil> <nil> [] <nil> map[] fmt.Println(b == nil, m == nil) // ture true }
聚合类型的零值
聚合类型的零值为 每个元素或字段都是对应该类型的零值
, 常见的聚合类型有: array
, struct
package main import ( "fmt" ) type T struct { i int f float64 b [3]byte next *T } func main() { var t T fmt.Println(t) // {0 0 [0 0 0] <nil>} }
参考资源:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK