duanqinbi9029 2018-12-21 05:47
浏览 86
已采纳

如何在go中比较两个模板,示例得到了意外的结果

I want to compare two templates in Go, the simplified example below get an unexpected result. How to compare them?

https://play.golang.org/p/Q3eAxVEzcFp

I have tried DeepEqual but it does not work.

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
    "strings"
    "text/template"
)

// basicFunctions are the set of initial
// functions provided to every template.
var basicFunctions = template.FuncMap{
    "json": func(v interface{}) string {
        a, _ := json.Marshal(v)
        return string(a)
    },
    "split": strings.Split,
    "join":  strings.Join,
    "title": strings.Title,
    "lower": strings.ToLower,
    "upper": strings.ToUpper,
}

func main() {
    t1, _ := template.New("").Funcs(basicFunctions).Parse("{{.ID}}")
    t2, _ := template.New("").Funcs(basicFunctions).Parse("{{.ID}}")
    fmt.Println(reflect.DeepEqual(t1, t2)) // want to be true, actually false
}

I want to get a true answer.

  • 写回答

1条回答 默认 最新

  • douyi02577 2018-12-25 23:24
    关注

    Execute the two templates using the same data, but write each to a different buffer. Compare the bytes in the buffers. Repeat with different data until they diverge or you are satisfied that they are the same.

    t1, _ := template.New("").Funcs(basicFunctions).Parse("{{.ID}}")
    t2, _ := template.New("").Funcs(basicFunctions).Parse("{{.ID}}")
    var b1, b2 bytes.Buffer
    d := struct{ ID string }{ID: "test"}
    t1.Execute(&b1, d)
    t2.Execute(&b2, d)
    fmt.Println(bytes.Equal(b1.Bytes(), b2.Bytes())) // true
    

    https://play.golang.org/p/jz2Lbmf-4RY

    There should be some set of data inputs that would satisfy you that these templates are the same, given that they output the same bytes given the same inputs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂