作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我见过一些类似的问题,但找不到能解决我的问题的问题。
我有一个自定义 Money
类型,它使用一个将值格式化为字符串的函数作为 int64 的别名:
type Money int64
func (m *Money) Format() string {
abs := math.Abs(int64(*m))
dollars := int64(abs) / 100
cents := int64(abs) % 100
sign := ""
if *m < 0 {
sign = "-"
}
return fmt.Sprintf("%s$%d.%0.2d", sign, dollars, cents)
}
我有一个 HTML 模板,我传递了一个数据结构。该结构有一个发票项目列表,每个项目都有一个 Money 字段,另一个 Money 字段包含总计。
type InvoiceItem {
// ...
Cost money.Money
}
type data struct {
Name string
Items []*model.InvoiceItem
StartDate time.Time
EndDate time.Time
Total money.Money
}
我将 data
传递到我的模板并执行它:
t := template.Must(template.New(title).Parse(templateString))
t.Execute(&buf, data)
在我的模板中,我遍历了发票项目并调用了 Money
对象上的 Format
函数。这有效:
{{range .Items}}
<tr>
<td>{{.Description}}</td>
<td>{{.Cost.Format}}</td>
</tr>
{{end}}
稍后我尝试打印总字段:
<td><strong>{{ .Total.Format }}</strong></td>
我的模板抛出一个错误:
... executing "Invoice Items" at <.Total.Format>: can't evaluate field Format in type money.Money
为什么当我遍历发票项目列表时,我可以在 Money
字段上调用 Format
,但我不能在 上调用它>data.Total
对象?从错误消息看来,模板知道 Total
的类型是 Money
,那么问题是什么?
最佳答案
看起来您的 data
结构未导出。这样做:
type Data struct {
}
关于go - 如何在自定义类型上调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53625439/
我是一名优秀的程序员,十分优秀!