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 1

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

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -