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

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

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题