printf-args-num-ok?

Cf7c364c6463eb8a1f1bb5c4a2e583a6?s=47 decafe09
February 24, 2018

 printf-args-num-ok?

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

Cf7c364c6463eb8a1f1bb5c4a2e583a6?s=128

decafe09

February 24, 2018
Tweet

Transcript

  1. printf - args num ok? Umeda.go #3 2018 - 02

    - 24 @decafe09
  2. fmt.Printf fmt.Printf("%s", "moji")

  3. fmt.Printf fmt.Printf("%s", "moji", "yobun")  

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

    # ここで気づける moji%!(EXTRA string=yobun)
  5. 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) }
  6. fmt.Printf $ go build # ここでは気づけない $ go run main.go

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

    arg but has 2 args go vet ! curl     " go vet CI  go vet
  8. 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...) }
  9. 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  
  10. Humm... format := "%s" fmt.Printf(format, "moji", ”yobun")

  11. Humm... $ go build # ここでは気づけない $ go vet #

    ここでは気づけない $ go run main.go # ここで気づける moji%!(EXTRA string=yobun) http ! %  #  &$"%  
  12. 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$ 
  13. Thinking... "0(' !  0(',1#%$ /0( $   !

     +.)*format !format  !&-...
  14. 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 }
  15. 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/
  16. Check $ go run main.go panic: format error: moji%!(EXTRA string=yobun)

  17. Profile   decafe09      

  18.