← 中文资源

简体中文版本

Go vet: Printf 的 %d 参数类型不正确

修复 go vet 的 printf 告警:格式动词与参数类型不匹配,并理解为何 fmt 看似仍能打印出正确结果。

阅读英文原文

症状

go vet 报出类似 Printf format %d has arg x of wrong type string 的失败,而程序在运行时似乎仍能打印出看似合理的结果。

诊断

把动词、参数类型与调用点结合起来看:

count := "5"
log.Printf("count=%d", count) // vet: %d with string

同时检查参数顺序——一旦某个值错位,其后每个动词都会失配。

修复

让动词与类型对齐,并为自定义类型实现 String():

log.Printf("count=%s", count)   // string

type Money struct{ Cents int }
func (m Money) String() string { return fmt.Sprintf("%.2f", float64(m.Cents)/100) }
log.Printf("total=%s", Money{1250})

验证

go vet ./... 通过,并用一个断言精确格式化输出的单元测试确认修复;否则 fmt 会静默输出 %!d 占位符而不报错。