因此,我使用以下命令创建了一个字符串变量
name := "Batman"
age := 38
nameAndAge = fmt.Sprintf("%s %d", name, age)
在另一个函数中,我可以访问变量
nameAndAge
。现在,我想找回在Sprintf
中使用的两个变量。我可以考虑的一种忽略的方法是基于分隔符将其拆分并创建变量。我想知道是否有任何功能可以做到这一点?喜欢,
var name string
var age int
// " " is the separator here
fmt.ReverseSprintf(nameAndAge, " ", name, age)
谢谢您的帮助。
最佳答案
在某种程度上,这是 fmt.Sscanf()
。引用 fmt
: Scanning的doc文件:
Scanf, Fscanf, and Sscanf parse the arguments according to a format string, analogous to that of 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)
它输出(在Go Playground上尝试):
Batman 38
Batman 38
我写“在某种程度上”是因为您的示例非常简单。如果您的
name
将包含空格,则上面的示例将损坏:name := "Batman Robin"
// The rest is the same
输出为:
Batman Robin 38
error expected integer
Batman 0
这样做的原因是因为在我们的
string
格式中,我们使用空格分隔输入,并且如果空格本身包含在输入中,则反转过程无法分辨出差异。扫描功能还将输入中的换行符视为空格以及其他差异。
关于string - 有没有办法做反Sprintf结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61411511/