dqdpz60048 2016-02-24 18:15
浏览 104
已采纳

在golang文本/模板中解引用指针

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条回答 默认 最新

  • douji6667 2016-02-24 18:53
    关注

    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.

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

报告相同问题?

悬赏问题

  • ¥15 wpf程序使用过程中异常奔溃
  • ¥15 多目标优化算法在与其他算法数据对比结果判断
  • ¥15 CPTN和EAST,主干网络是VGG16,请问在ICDAR2015数据集上训练之后,CPTN和EAST模型的大小为多少
  • ¥15 按颜色进行点云分割-python
  • ¥15 Matlab如何实现汽车变道切入场景的批量仿真
  • ¥15 无刷电机要通过什么才能做各种动作
  • ¥15 VS2010通过OnCtlColor函数改变radio控件字体的颜色为白色,但是程序运行后发现不起作用,怎么办?
  • ¥15 Qt中实现子线程和管理线程类之间实时通信
  • ¥15 cacls 命令如何解除锁定文件夹?
  • ¥50 C++使用TWAIN协议如何实现A3幅面扫描仪扫描A4横向