
Go 中整型和浮点型是值类型,没有 nil 状态;其“空”实际指代零值(如 0、0.0),需直接与零比较,而非使用 == nil。若需表示“未设置”,应改用指针类型并判空。
go 中整型和浮点型是值类型,没有 `nil` 状态;其“空”实际指代零值(如 `0`、`0.0`),需直接与零比较,而非使用 `== nil`。若需表示“未设置”,应改用指针类型并判空。
在 Go 语言中,int、int32、float64 等基础数值类型属于值类型(value type),它们在声明后会自动初始化为对应的零值(zero value):整数为 0,浮点数为 0.0,布尔为 false,字符串为 ""。因此,nil 对这些类型完全不合法——编译器会直接报错,例如:
var foo float32
if foo == nil { // ❌ 编译错误:cannot compare float32 with nil
// ...
}✅ 正确做法一:直接与零值比较
适用于明确接受零为有效业务值(如温度 0℃、账户余额 0 元),且无需区分“未设置”与“设为零”:
var age int = 0
if age == 0 {
fmt.Println("age is zero (or uninitialized)")
}
var price float64 = 0.0
if price == 0.0 {
fmt.Println("price is zero")
}⚠️ 注意:此方式无法区分“用户主动设为 0”和“变量未初始化/未赋值”。若业务逻辑需要表达“未提供”这一状态,则必须升级类型。
✅ 正确做法二:使用指针类型(*int、*float64)
指针是引用类型,可为 nil,天然支持“存在/不存在”的语义:
package main
import "fmt"
func main() {
var score *float64 // nil by default
if score == nil {
fmt.Println("score not provided") // ✅ 安全判空
} else {
fmt.Printf("score: %.2f\n", *score)
}
// 设置值示例
val := 95.5
score = &val
if score != nil {
fmt.Printf("score is set to: %.2f\n", *score) // 输出:95.50
}
}? 进阶建议:
- API 请求结构体中,对可选数值字段优先使用指针(如 Age *int),便于 JSON 解析时保留 null 语义;
- 使用 omitempty 标签配合指针,可实现零值字段自动忽略序列化:
type User struct { Name string `json:"name"` Age *int `json:"age,omitempty"` // nil 字段不出现在 JSON 中 } - 若需频繁判空且避免指针解引用风险,可封装为自定义类型或使用 github.com/google/uuid 风格的 Valid 字段(如 type NullableInt struct { Value int; Valid bool })。
总结:Go 没有“空数值”的概念,只有零值;nil 仅适用于指针、切片、map、channel、func 和 interface。选择 == 0 还是 == nil,本质是建模决策——取决于你的业务是否需要区分“零”与“未设置”。

















