go runtime_error ai_generated true

template: :1:2: executing "" at <.Field>: can't evaluate field Field in type struct { ... }

ID: go/template-cannot-evaluate-field-in-type-struct

Also available as: JSON · Markdown · 中文
96%Fix Rate
88%Confidence
1Evidence
2023-06-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
go1.20 active
go1.21 active
go1.22 active

Root Cause

A Go template references a field or method that does not exist on the data structure passed to Execute().

generic

中文

Go 模板引用了传递给 Execute() 的数据结构中不存在的字段或方法。

Official Documentation

https://pkg.go.dev/text/template#hdr-Actions

Workarounds

  1. 96% success Add the missing field to the struct: type Data struct { Field string } or rename the template reference to match an existing field
    Add the missing field to the struct: type Data struct { Field string } or rename the template reference to match an existing field
  2. 93% success Use template.FuncMap to define a custom function that retrieves the value: tmpl.Funcs(template.FuncMap{"getField": func(d Data) string { return d.ExistingField }})
    Use template.FuncMap to define a custom function that retrieves the value: tmpl.Funcs(template.FuncMap{"getField": func(d Data) string { return d.ExistingField }})
  3. 90% success Pass a map instead of a struct: data := map[string]interface{}{"Field": value}; tmpl.Execute(w, data)
    Pass a map instead of a struct: data := map[string]interface{}{"Field": value}; tmpl.Execute(w, data)

中文步骤

  1. 在结构体中添加缺失的字段:type Data struct { Field string } 或将模板引用重命名为匹配现有字段
  2. 使用 template.FuncMap 定义自定义函数来获取值:tmpl.Funcs(template.FuncMap{"getField": func(d Data) string { return d.ExistingField }})
  3. 传递映射而不是结构体:data := map[string]interface{}{"Field": value}; tmpl.Execute(w, data)

Dead Ends

Common approaches that don't work:

  1. Add the field to the template but not to the struct 80% fail

    The error is from the missing field in the struct, not the template

  2. Use {{.}} to print the whole struct and ignore the error 70% fail

    Doesn't solve the underlying issue; the template may still fail for other fields

  3. Change the struct to have a field with a different name 60% fail

    The template expects the exact field name; renaming breaks the template match