【问题标题】:Templates: accessing nested fields of slice of structs模板:访问结构切片的嵌套字段
【发布时间】:2021-11-18 19:08:03
【问题描述】:

我想使用 go 模板输出slice[0].type。打印工作时:

{{ index .Slice 0 | printf "%+v" }} // {Type:api.Meter ShortType:Meter VarName:meter}

打印字段不会:

{{ index .Slice 0 | .Type }} // template: gen:43:26: executing "gen" at <.Type>: can't evaluate field Type in type struct { API string; Package string; Function string; BaseTypes []main.baseType; Types map[string]main.typeStruct; Combinations [][]string }

错误消息表明外部循环字段被评估,而不是index调用的结果。

访问切片嵌套字段的正确语法是什么?

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

    printf 是一个内置的模板函数。当您将index .Slice 0 链接到printf 时,该值将作为最后一个参数传递给printf。访问Type 字段不是函数调用,你不能链接到它。链中的.Type 将在当前“点”上进行评估,链接不会改变点。​​p>

    使用括号对切片表达式进行分组,然后应用字段选择器:

    {{ (index .Slice 0).Type }}
    

    示例测试:

    type Foo struct {
        Type string
    }
    
    t := template.Must(template.New("").Parse(`{{ (index .Slice 0).Type }}`))
    
    params := map[string]interface{}{
        "Slice": []Foo{{Type: "Bar"}},
    }
    
    if err := t.Execute(os.Stdout, params); err != nil {
        panic(err)
    }
    

    哪些输出(在Go Playground 上试试):

    Bar
    

    【讨论】:

    • 您能否补充一下为什么管道操作员不应该在这里工作?感谢解决方案,但它没有点击为什么我的方法有缺陷。
    • 查看编辑后的答案。
    猜你喜欢
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多