Go 中的初始化
2024-09-02 15:13:54
# Go
Go 语言会在声明变量类型的时候进行初始化,如果没有指定值,那将会使用零值。各种类型的零值:
- int: 0
- float: 0.0
- bool: false
- string: “”
- 切片: []
- 指针、函数、接口: nil
- 结构体: 由属性的零值组成
需要注意的是,Go 语言中声明(declaration)和定义(definition)都会为变量分配空间。意思是不在需要像 Java 那样必须调用 new 来构造对象。
举例如下:
1 | package main |
输出为:
1 | Declaration StructB: |
可以发现声明的变量也可以直接使用,并且属性都被赋予了零值。