doukuiqian5345 2019-03-30 23:38
浏览 543
已采纳

从golang模板调用数组的方法

So in my main.go I have a struct and a method that I can call from inside main.go without a problem. Imagine it being like this:

type Test struct {
    val1 float32
    val2 float32
}

func (t Test) callMethod() float32 {
    return t.val1 / t.val2
}

I am calling the template like this and as data I am giving an array of the Test structs, like this:

var testvar1 Test
var testvar2 Test
var teststructs [] Test
teststructs = append(teststructs, testvar1)
teststructs = append(teststructs, testvar2)
tpl.ExecuteTemplate(w, "testpage.gohtml", teststructs)

Inside the template I am trying to call the callMethod like this

{{range .}}
    {{ .callMethod }}
{{end}}

But I am getting the following error:

executing "testpage.gohtml" at <.callMethod>: can't evaluate field callMethod in type main.Test

Has anyone an Idea what I am doing wrong and has a solution for this? I am trying to fix it since many hours and I am so frustrated at this point.

  • 写回答

1条回答 默认 最新

  • duanbimo7212 2019-03-31 02:03
    关注

    Your Teststruct has no exported fields/methods, i.e. fields/methods within the struct that are used within the template have to start with a capital letter.

    Update the method name to CallMethod

    func (t Test) CallMethod() float32 {
        return t.val1 / t.val2
    }
    

    and the template:

    const tmpl = `
    {{range .}}
       {{.CallMethod}}
    {{end}}
    `
    

    see the code https://play.golang.org/p/Vud7ipJ_Vyr

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?