有没有办法做反Sprintf结果

所以,我使用创建了一个字符串变量

name := "Batman"
age := 38
nameAndAge = fmt.Sprintf("%s %d", name, age)

In another function, I can access the variable nameAndAge. Now I want to get back both the variables that I used in Sprintf. One oblivious way that I can think about is to split it based on the separator and create the variable. I wanted to know if there's any function available for doing that?

喜欢,

var name string
var age int
// " " is the separator here
fmt.ReverseSprintf(nameAndAge, " ", name, age)

谢谢您的帮助。

评论
  • 赫连迎蓉
    赫连迎蓉 回复

    To some extent its possible, there's fmt.Sscanf() for this. Quoting from package doc of fmt: Scanning:

    Scanf,Fscanf和Sscanf根据类似于Printf的格式字符串解析参数。

    请参阅以下示例:

    name := "Batman"
    age := 38
    output := fmt.Sprintf("%s %d", name, age)
    
    fmt.Println(output)
    
    var name2 string
    var age2 int
    if _, err := fmt.Sscanf(output, "%s %d", &name2, &age2); err != nil {
        fmt.Println("error", err)
    }
    fmt.Println(name2, age2)
    

    It outputs (try it on the Go Playground):

    Batman 38
    Batman 38
    

    I wrote "to some extent" is because your example was quite simple. If your name would have contained spaces, the above example would've broke:

    name := "Batman Robin"
    // The rest is the same
    

    输出为:

    Batman Robin 38
    error expected integer
    Batman 0
    

    The reason for this is because in our format string we used space to separate inputs, and if the space itself is contained in the input, the reversing process can't tell the difference. Also the scanning functions treat newlines in the input as spaces, among other differences.