在golang的text/template中解引用指针。

huangapple go评论89阅读模式
英文:

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 &quot;mytemplate&quot; at &lt;eq .ID 5&gt;: 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(&quot;&quot;).Funcs(template.FuncMap{
		&quot;Deref&quot;: func(i *int) int { return *i },
	}).Parse(src))
	i := 5
	m := map[string]interface{}{&quot;ID&quot;: &amp;i}
	if err := t.Execute(os.Stdout, m); err != nil {
		fmt.Println(err)
	}
}

const src = `{{if eq 5 (Deref .ID)}}It&#39;s five.{{else}}Not five: {{.ID}}{{end}}`

Output:

It&#39;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.:

	&quot;Cmp&quot;:   func(i *int, j int) bool { return *i == j },

And calling it from the template:

{{if Cmp .ID 5}}It&#39;s five.{{else}}Not five: {{.ID}}{{end}}

Output is the same. Try these on the Go Playground.

huangapple
  • 本文由 发表于 2016年2月25日 02:15:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/35609903.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定