go - How to ignore extra fields for fmt.Sprintf -
i have golang program reads string parameter command line , passes fmt.sprintf function. let's tmp_str target string command line.
package main import "fmt" func main() { tmp_str := "hello %s" str := fmt.sprintf(tmp_str, "world") fmt.println(str) }
in cases, program pass completed string "hello friends", instead of string template.. program panic , return:
hello friends%!(extra string=world)
so, how ignore fields fmt.sprintf?
yes can it, slicing arguments pass variadic sprintf
function:
func truncatingsprintf(str string, args ...interface{}) (string, error) { n := strings.count(str, "%s") if n > len(args) { return "", errors.new("unexpected string:" + str) } return fmt.sprintf(str, args[:n]...), nil } func main() { tmp_str := "hello %s %s %s" // don't hesitate add many %s here str, err := truncatingsprintf(tmp_str, "world") // or many arguments here if err != nil { fmt.println(err) return } fmt.println(str) }
demonstration 2 (a different version outputting when there's more %s arguments)
but don't use dynamic formatted strings, isn't secure , if want accept any string, should adapt code no choke on %%s
. if venture far, should have @ templates (which let use named strings, , missing 1 wouldn't have last one).
Comments
Post a Comment