英文:
Dereferencing pointers in a golang text/template
问题
在golang的模板中,当简单输出值时,指针似乎会自动解引用。当.ID
是指向int
的指针时,
{{.ID}}
输出 5
但是当我尝试在管道中使用它,{{if eq .ID 5}}
我会得到一个错误。
executing "mytemplate" at <eq .ID 5>: error calling eq: invalid type for comparison
在模板管道中如何对指针进行解引用?
英文:
Inside a golang template when simply outputting values it seems that pointers are automatically dereferenced. When .ID
is a pointer to an int
,
{{.ID}}
outputs 5
But when I try to use it in a pipeline, {{if eq .ID 5}}
I get an error.
executing "mytemplate" at <eq .ID 5>: error calling eq: invalid type for comparison
How do I do a dereference of a pointer inside a template pipeline?
答案1
得分: 14
一种方法是注册一个自定义函数来取消引用指针,这样你就可以将结果与你想要的任何内容进行比较,或者对其进行其他操作。
例如:
func main() {
t := template.Must(template.New("").Funcs(template.FuncMap{
"Deref": func(i *int) int { return *i },
}).Parse(src))
i := 5
m := map[string]interface{}{"ID": &i}
if err := t.Execute(os.Stdout, m); err != nil {
fmt.Println(err)
}
}
const src = `{{if eq 5 (Deref .ID)}}It's five.{{else}}Not five: {{.ID}}{{end}}`
输出:
It's five.
或者你可以使用另一个自定义函数,该函数接受一个指针和一个非指针,并进行比较,例如:
"Cmp": func(i *int, j int) bool { return *i == j },
并在模板中调用它:
{{if Cmp .ID 5}}It's five.{{else}}Not five: {{.ID}}{{end}}
输出结果相同。你可以在Go Playground上尝试这些代码。
英文:
One way is to register a custom function which dereferences the pointer, so you can compare the result to whatever you want to or do anything else with it.
For example:
func main() {
t := template.Must(template.New("").Funcs(template.FuncMap{
"Deref": func(i *int) int { return *i },
}).Parse(src))
i := 5
m := map[string]interface{}{"ID": &i}
if err := t.Execute(os.Stdout, m); err != nil {
fmt.Println(err)
}
}
const src = `{{if eq 5 (Deref .ID)}}It's five.{{else}}Not five: {{.ID}}{{end}}`
Output:
It's five.
Alternatively you could use a different custom function which would take a pointer and a non-pointer, and do the comparision, e.g.:
"Cmp": func(i *int, j int) bool { return *i == j },
And calling it from the template:
{{if Cmp .ID 5}}It's five.{{else}}Not five: {{.ID}}{{end}}
Output is the same. Try these on the Go Playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论