fmt.Sscanf for structs

huangapple go评论85阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年6月7日 15:59:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/44406814.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定