当我运行此代码时
package main
import ("fmt")
func main() {
i := 5
fmt.Println("Hello, playground %d",i)
}
Run Code Online (Sandbox Code Playgroud)
(游乐场链接)
我得到以下警告:prog.go:5:Println调用可能的格式化指令%d Go vet退出.
这样做的正确方法是什么?
Sch*_*ern 36
fmt.Println不做格式化的事情%d.相反,它使用其参数的默认格式,并在它们之间添加空格.
fmt.Println("Hello, playground",i) // Hello, playground 5
Run Code Online (Sandbox Code Playgroud)
如果您想要printf样式格式化,请使用fmt.Printf.
fmt.Printf("Hello, playground %d\n",i)
Run Code Online (Sandbox Code Playgroud)
而且你不需要特别关注这种类型.%v通常会弄清楚.
fmt.Printf("Hello, playground %v\n",i)
Run Code Online (Sandbox Code Playgroud)
警告是告诉您%d在调用时有格式指令(在这种情况下)Println。这是警告,因为Println 不支持格式指令。格式函数Printf和支持这些指令Sprintf。fmt软件包文档中对此进行了详细说明。
如您在运行代码时清楚看到的那样,输出为
Hello, playground %d 5
Run Code Online (Sandbox Code Playgroud)
因为Println它的文档说的是-它打印其参数,后跟换行符。将其更改为Printf,这可能是您想要的,然后得到了:
Hello, playground 5
Run Code Online (Sandbox Code Playgroud)
大概是您想要的。