go runtime_error ai_generated true

模板::1:2: 执行 "" 在 <.Field>: 无法在类型 struct { ... } 中评估字段 Field

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

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

其他格式: JSON · Markdown 中文 · English
96%修复率
88%置信度
1证据数
2023-06-12首次发现

版本兼容性

版本状态引入弃用备注
go1.20 active
go1.21 active
go1.22 active

根因分析

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

English

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

generic

官方文档

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

解决方案

  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)

无效尝试

常见但无效的做法:

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

    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% 失败

    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% 失败

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