呼叫具有可能的格式指令

时间:2018-12-28 16:39:13

标签: go

当我运行这段代码

package main
import ("fmt")
func main() {
    i := 5
    fmt.Println("Hello, playground %d",i)
}

playground link

我收到以下警告: prog.go:5:Println调用具有可能的格式指令%d 兽医退出了。

执行此操作的正确方法是什么?

3 个答案:

答案 0 :(得分:14)

fmt.Println不会像%d这样格式化。相反,它使用其参数的默认格式,并在参数之间添加空格。

fmt.Println("Hello, playground",i)  // Hello, playground 5

如果要设置printf样式格式,请使用fmt.Printf

fmt.Printf("Hello, playground %d\n",i)

您不需要特别说明类型。 %v通常会弄清楚。

fmt.Printf("Hello, playground %v\n",i)

答案 1 :(得分:4)

警告是告诉您在调用%d时有一个格式化指令(在这种情况下为Println)。这是警告,因为Println 不支持格式化指令。格式函数PrintfSprintf支持这些指令。 fmt package documentation中对此进行了详细说明。

正如您在运行代码时清楚看到的那样,输出为

Hello, playground %d 5

因为Println会执行其文档中所说的内容-它会打印其参数并在后面加上换行符。将其更改为and you get this instead,可能是您想要的Printf

Hello, playground 5

大概是您想要的。

答案 2 :(得分:-1)

package main
import ("fmt")
func main() {
    i := 5
    fmt.Println("Hello, playground %d",i)
}
===================================================
package main
import ("fmt")
func main() {
    i := 5
    fmt.Printf("Hello, playground %d",i)
}