dongmi8980 2017-06-07 07:59
浏览 75

fmt.Sscanf用于结构

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
", 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条回答 默认 最新

  • doujilou3903 2017-06-07 15:52
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类