How to ignore extra fields for fmt.Sprintf

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

package main

import "fmt"

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

In some cases, a program passes a completed string, such as "Hello Friends," instead of a string pattern. The program will panic and return:

Hello friends%! (EXTRA string = world)

So how to ignore extra fields for fmt.Sprintf?

+4
source share
5 answers

Yes, you can do this by cutting the arguments you pass to the variable Sprintf:

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

2 ( , % s, )

, , , %%s. , , , templates ( , , , t ).

+7

Volker, :

package main

import (
    "fmt"
    "strings"
)

func main() {
    tmp_str := "hello %s"

    res := tmp_str
    if strings.Count(tmp_str, "%s") == 1 {
        res = fmt.Sprintf(tmp_str, "world")
    }
    fmt.Println(res)
}
+4

, % s , :

Hello Friends%.0s

:

Hello Friends%.s

:

+2
source

I use this one (which can be extended)

Sprintf("Hello"+"%[2]s", "World", "")
Sprintf("Hello %s"+"%[2]s", "World", "")
0
source

You cannot do this.

You need to find another solution.

-4
source

Source: https://habr.com/ru/post/1626225/


All Articles