gpt4 book ai didi

go - go中如何比较两个模板,例子得到了意想不到的结果

转载 作者:IT王子 更新时间:2023-10-29 02:08:05 25 4
gpt4 key购买 nike

我想在 Go 中比较两个模板,下面的简化示例得到了意想不到的结果。如何比较?

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

我已经尝试过 DeepEqual,但它不起作用。

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
}

我想得到一个 true 的答案。

最佳答案

使用相同的数据执行两个模板,但将每个模板写入不同的缓冲区。比较缓冲区中的字节。重复不同的数据,直到它们出现分歧或您对它们相同感到满意为止。

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

应该有一些数据输入会让您满意这些模板是相同的,因为它们在给定相同输入的情况下输出相同的字节。

关于go - go中如何比较两个模板,例子得到了意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53879767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com