Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore extra fields for fmt.Sprintf

Tags:

go

I have a Golang program that reads a string parameter from command line and passes it to the fmt.Sprintf function. Let's say tmp_str is the target string from command line.

package main

import "fmt"

func main() {
    tmp_str := "hello %s"
    str := fmt.Sprintf(tmp_str, "world")
    fmt.Println(str)
}

In some cases, the program will pass a completed string like "Hello Friends", instead of a string template.. The program would panic and return:

Hello Friends%!(EXTRA string=world)

So, how to ignore the extra fields for fmt.Sprintf?

like image 941
Patrick Avatar asked Jan 27 '16 16:01

Patrick


People also ask

What is sprintf() function in Golang?

Golang Sprintf () is a built-in function that formats according to a format specifier and returns the resulting string. The Sprintf () function accepts a string that needs to be formatted and returns the formatted string. The Sprintf () function takes a string and the value we need to format.

How to print a string using sprintf() function in Python?

The Sprintf () function returns a String and does not print the string. So after storing it in a variable, we can print the string. See the following example. // hello.go package main import ( "fmt" ) func main() { const name, age = "Krunal", 27 s := fmt.Sprintf ( "%s is %d years old. ", name, age) print (s) }

Is it possible to slice the arguments of a variadic sprintf function?

Yes you can do it, by slicing the arguments you pass to the variadic Sprintf function:


1 Answers

Yes you can do it, by slicing the arguments you pass to the 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 to 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 even when there's more %s than arguments)

But you don't usually use dynamic formatted strings, this isn't secure and if you want to accept any string, you should also adapt this code to no choke on %%s. If you venture this far, then you should probably have a look at templates (which would let you use named strings, and thus the missing one wouldn't have to be the last one).

like image 173
Denys Séguret Avatar answered Sep 28 '22 11:09

Denys Séguret