dtll2016 2015-07-08 08:28
浏览 43
已采纳

使用具有多个返回值的方法

I'm trying to write a template (using html/template) and passing it a struct that has some methods attached to it, many of which return multiple values. Is there any way of accessing these from within the template? I'd like to be able to do something like:

package main

import (
        "fmt"
        "os"
        "text/template"
)

type Foo struct {
    Name string
}

func (f Foo) Baz() (int, int) {
    return 1, 5
}

const tmpl = `Name: {{.Name}}, Ints: {{$a, $b := .Baz}}{{$a}}, {{b}}`

func main() {

    f := Foo{"Foo"}

    t, err := template.New("test").Parse(tmpl)
    if err != nil {
        fmt.Println(err)
    }

    t.Execute(os.Stdout, f)

}

But obviously this doesn't work. Is there no way around it?

I've considered creating an anonymous struct in my code:

data := struct {
    Foo
    a   int
    b   int
}{
    f,
    0,
    0,
}
data.a, data.b = f.Baz()

And passing that in, but would much prefer to have something in the template. Any ideas? I also tried writing a wrapper function which I added to funcMaps but could never get that to work at all.

Thanks for any suggestions!

  • 写回答

3条回答 默认 最新

  • duanhao8540 2015-07-08 10:52
    关注

    You won't be able to call a function that returns two values in a template unless one of those values is an error. This is so that your template is guaranteed to work at runtime. There is a great answer that explains that here, if you're interested.

    To solve your problem you need to either 1) break your function into two separate getter functions that you can call in the appropriate place in your template; or 2) have your function return a simple struct with the values inside.

    I can't tell which would be better for you because I really have no idea what your implementation requires. Foo and Baz don't give many clues. ;)

    Here is a quick-n-dirty example of option one:

    type Foo struct {
        Name string
    }
    
    func (f Foo) GetA() (int) {
        return 1
    }
    
    func (f Foo) GetB() (int) {
        return 5
    }
    

    And then modify the template accordingly:

    const tmpl = `Name: {{.Name}}, Ints: {{.GetA}}, {{.GetB}}`
    

    Hopefully this is of some help. :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图