
在 go 中,可通过解引用操作符 `*` 将 `*time.time` 等指针类型安全转为对应的值类型 `time.time`,前提是该指针非 nil;否则需先判空以避免 panic。
Go 中的指针解引用(dereferencing)是基础但关键的操作:* 符号在声明时表示“指向某类型的指针”(如 *time.Time),而在表达式中则表示“取指针所指向的值”。这与 C 语言语义一致,但 Go 更加类型安全且禁止指针算术。
例如,针对你定义的结构体:
type Example struct {
CreatedDate *time.Time
}当你需要调用 time.Since(then)(其参数类型为 time.Time)时,若 CreatedDate 非 nil,可直接解引用:
if example.CreatedDate != nil {
elapsed := time.Since(*example.CreatedDate)
fmt.Printf("Elapsed: %v\n", elapsed)
} else {
fmt.Println("CreatedDate is not set")
}⚠️ 重要注意事项:
- 直接对 nil 指针解引用(如 *nilTimePtr)会触发运行时 panic:invalid memory address or nil pointer dereference;
- 因此,务必在解引用前进行 nil 检查——这是 Go 中处理可选时间字段的安全实践;
- 若逻辑上允许默认时间(如“零时间”或当前时间),也可提供 fallback:
t := time.Now()
if example.CreatedDate != nil {
t = *example.CreatedDate
}
elapsed := time.Since(t)✅ 总结:Go 中“指针 → 值”的转换唯一且标准的方式就是使用一元 * 操作符解引用,它不是类型断言(x.(T) 仅用于接口),也不涉及任何强制转换(cast)——Go 不支持 C 风格的类型强转。牢记 &x 取地址,*p 取值,二者成对出现,是理解 Go 内存模型的基石。










