登录
首页 >  Golang >  Go问答

如何调用自定义类型的函数

来源:stackoverflow

时间:2024-04-17 08:09:36 137浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《如何调用自定义类型的函数》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

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

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

    {{.description}}
    {{.cost.format}}

{{end}}

稍后我尝试打印总计字段:

{{ .total.format }}

我的模板抛出错误:

... 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 { 

}

今天关于《如何调用自定义类型的函数》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>