gpt4 book ai didi

go - 如何在自定义类型上调用函数

转载 作者:数据小太阳 更新时间:2023-10-29 03:37:52 24 4
gpt4 key购买 nike

我见过一些类似的问题,但找不到能解决我的问题的问题。

我有一个自定义 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com