doswy02440 2014-08-07 11:24
浏览 25

去模板构造

I have a Go template that should resolve to a struct. How can I convert the bytes.Bufferresult from template execute function back to the struct. Playground

package main

import (
    "bytes"
    "encoding/gob"
    "fmt"
    "log"
    "text/template"
)

type Data struct {
    Age      int
    Username string
    SubData  SubData
}
type SubData struct {
    Name string
}

func main() {
    s := SubData{Name: "J. Jr"}
    d := Data{Age: 26, Username: "HelloWorld", SubData: s}
    tmpl := "{{ .SubData }}"
    t := template.New("My template")
    t, _ = t.Parse(string(tmpl))
    buffer := new(bytes.Buffer)
    t.Execute(buffer, d)
    fmt.Println(buffer)

    // writing
    enc := gob.NewEncoder(buffer)
    err := enc.Encode(s)
    if err != nil {
        log.Fatal("encode error:", err)
    }

    // reading
    buffer = bytes.NewBuffer(buffer.Bytes())
    e := new(SubData)
    dec := gob.NewDecoder(buffer)
    err = dec.Decode(e)
    if err != nil {
        log.Fatal("decode error:", err)
    }
    fmt.Println(e, err)
}
  • 写回答

1条回答 默认 最新

  • dongxianghuan3587 2014-08-07 11:38
    关注

    You cannot. This is plain simply impossible.

    But why on earth would anybody want to do something like this? Why don't you just send your Data directly via gob and decode it directly? Why creating a textual representation which you gob?

    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算