duanqia9034
duanqia9034
2018-12-28 16:39
浏览 214
已采纳

呼叫具有可能的格式指令

When I run this code

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

(playground link)

I get the following warning: prog.go:5: Println call has possible formatting directive %d Go vet exited.

What is a proper way to do this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongyun7897
    dongyun7897 2018-12-28 16:46
    已采纳

    fmt.Println doesn't do formatting things like %d. Instead, it uses the default format of its arguments, and adds spaces between them.

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

    If you want printf style formatting, use fmt.Printf.

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

    And you don't need to be particular about the type. %v will generally figure it out.

    fmt.Printf("Hello, playground %v
    ",i)
    
    点赞 评论
  • doushichun9409
    doushichun9409 2018-12-28 16:46

    The warning is telling you you have a formatting directive (%d in this case) in a call to Println. This is a warning because Println does not support formatting directives. These directives are supported by the formatted functions Printf and Sprintf. This is explained thoroughly in the fmt package documentation.

    As you can plainly see when you run your code, the output is

    Hello, playground %d 5
    

    Because Println does what its docs say - it prints its arguments followed by a line break. Change that to Printf, which is likely what you intended, and you get this instead:

    Hello, playground 5
    

    Which is presumably what you intended.

    点赞 评论
  • duan00529
    duan00529 2019-08-10 10:10

    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)
    }

    </div>
    
    点赞 评论

相关推荐