英文:
fmt.Sscanf for structs
问题
我有一些以fmt.Sprintf("%+v", d)
的形式序列化的数据,其中d
是一个struct
实例。有没有办法将其扫描回来?我尝试使用fmt.Sscanf()
,但是下面的代码失败了(Go Playground)。
package main
import (
"fmt"
)
type data struct {
f int
}
func main() {
x := data{1}
s := fmt.Sprintf("%+v", x)
var y data
n, err := fmt.Sscanf(s, "%+v", &y)
fmt.Printf("s=%s, n=%d, err=%+v, y=%+v\n", s, n, err, y)
}
输出结果为:
s={f:1}, n=0, err=can't scan type: *main.data, y={f:0}
有没有办法将结构体扫描回来?
英文:
I have data which was previously serialized as fmt.Sprintf("%+v", d)
, d
being a struct
instance. Is there a way to scan it back? My naive attempt of using fmt.Sscanf()
below is failing (Go Playground).
package main
import (
"fmt"
)
type data struct {
f int
}
func main() {
x := data{1}
s := fmt.Sprintf("%+v", x)
var y data
n, err := fmt.Sscanf(s, "%+v", &y)
fmt.Printf("s=%s, n=%d, err=%+v, y=%+v\n", s, n, err, y)
}
The output is:
s={f:1}, n=0, err=can't scan type: *main.data, y={f:0}
Is there a way to scan the struct back?
答案1
得分: 2
很不幸,fmt
包无法生成严格可解析的输出。幸运的是,Go语言还有其他用于编组数据的包,使用起来同样简单。
我建议使用json
来处理简单的情况:
s, err := json.Marshal(data)
// 检查 err
err = json.Unmarshal(s, data)
json
将生成类似于printf的输出,但符合确保可解析的标准。如果你的目标是解析仅以Printf
形式存在的数据,可能会比较困难。
英文:
Unfortunately the fmt
package doesn't produce strictly parseable output. Thankfully go has other packages for marshaling data which should be just as easy to use.
I'd recommend json
for something simple:
s, err := json.Marshal(data)
// Check err
err = json.Unmarshal(s, data)
json
will produce output which is somewhat similar to printf, but conforming to a standard which ensures it can be parsed. If your goal is to parse data that exists only in Printf
'd form you may be out of luck.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论