Upgrade to Pro — share decks privately, control downloads, hide ads and more …

printf-args-num-ok?

decafe09
February 24, 2018

 printf-args-num-ok?

goでprintfの引数の数をチェックするときの諸々について。

decafe09

February 24, 2018
Tweet

More Decks by decafe09

Other Decks in Programming

Transcript

  1. fmt.Printf $ go build # ここでは気づけない $ go run main.go

    # ここで気づける moji%!(EXTRA string=yobun)
  2. fmt.Printf $ go build # ここでは気づけない $ go run main.go

    # ここで気づける moji%!(EXTRA string=yobun) func main() { http.HandleFunc( "/xxx", func(w http.ResponseWriter, r *http.Request) { fmt.Printf("%s", "moji", "yobun") return }, ) http.ListenAndServe(":8080", nil) }
  3. fmt.Printf $ go build # ここでは気づけない $ go run main.go

    # ここでは気づけない $ curl localhost:8080/xxx # ここで気づける moji%!(EXTRA string=yobun)
  4. go vet $ go vet ./main.go:6: Printf call needs 1

    arg but has 2 args go vet ! curl     " go vet CI  go vet
  5. go vet –printfuncs $ go vet –printfuncs=Infof ./main.go:6: Infof call

    needs 1 arg but has 2 args func Infof(format string, a ...interface{}) (n int, err error) { return fmt.Printf(format, a...) }
  6. go vet @ Go 1.10 $ go test ./main.go:6: Printf

    call needs 1 arg but has 2 args   go1.9.3 main.go:6: wrong number of args for format in Printf call: 1 needed but 2 args go1.10 main.go:6: Printf call needs 1 arg but has 2 args go test go vet   go test -printfuncs  
  7. Humm... $ go build # ここでは気づけない $ go vet #

    ここでは気づけない $ go run main.go # ここで気づける moji%!(EXTRA string=yobun) http ! %  #  &$"%  
  8. Background API6=3.;?>/2,BW!:20/)O   APIVK" C %!8>?4+?5JSAPIRFP XXNTL@YYNTLIEH  XXYYEH

     XX, YY O(&'!format!O(& %D 71? +<:20/GQ&72-/M%A format#xx,yy*9=-.;?U$ 
  9. Result func check(format string) error 1. format %! 2. format

    message 3. format %! 4. %!      func main() { format := "%s" err := check(format) if err != nil { panic(err) } fmt.Println(message(format)) } func message(format string) string { return fmt.Sprintf(format, "moji", "yobun") } func check(format string) error { pre := strings.Count(format, "%!") msg := message(format) post := strings.Count(msg, "%!") if post > pre { return errors.New("format error: " + msg) } return nil }
  10. OK All errors begin with the string "%!" followed sometimes

    by a single character (the verb) and end with a parenthesized description. https://golang.org/pkg/fmt/