在 golang 中取消引用指针 text/template
Dereferencing pointers in a golang text/template
在 golang template 中,当简单地输出值时,指针似乎会自动解除引用。当 .ID
是指向 int
、
的指针时
{{.ID}}
输出 5
但是当我尝试在管道中使用它时,{{if eq .ID 5}}
我得到一个错误。
executing "mytemplate" at <eq .ID 5>: error calling eq: invalid type for comparison
如何取消引用模板管道中的指针?
一种方法是注册一个取消引用指针的自定义函数,这样您就可以将结果与您想要的任何结果进行比较,或者用它做任何其他事情。
例如:
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.
上试试这些
在 golang template 中,当简单地输出值时,指针似乎会自动解除引用。当 .ID
是指向 int
、
{{.ID}}
输出 5
但是当我尝试在管道中使用它时,{{if eq .ID 5}}
我得到一个错误。
executing "mytemplate" at <eq .ID 5>: error calling eq: invalid type for comparison
如何取消引用模板管道中的指针?
一种方法是注册一个取消引用指针的自定义函数,这样您就可以将结果与您想要的任何结果进行比较,或者用它做任何其他事情。
例如:
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.
上试试这些