doucheng3811 2015-12-10 16:37
浏览 113
已采纳

将[] interface {}转换为非可变函数的参数

I am looking for an elegant way to unzip a list of arguments in Go. I do not want to use a variadic function for that purpose because in my usecase when writing a function I already know the number of arguments and I want to keep that part simple. However in my usecase the parameters arrive as []interface{}. I could not find a solution but hey maybe someone out there already knows how to do that?

package main

import (
    "fmt"
)

// NON-VARIADIC greater
func greet(n1, n2 string) {
    fmt.Printf("%s %s
", n1, n2)
}


func main() {
    l := []interface{}{"hello", "world"}

    // works
    greet(l[0].(string), l[1].(string))

    // does not work: "./args.go:20: not enough arguments in call to greet"
    //greet(l...)

    // is there something more elegant to unzip the list?
}
  • 写回答

2条回答 默认 最新

  • dpz1983 2015-12-10 17:38
    关注

    You could create a "generic" caller using reflect package, although this comes with overhead and lacks type safety. Unless you have some special case situation and don't know what you want to call in the code, it would be wiser to use the snippet from your question which works, but you consider not elegant.

    Example usage of reflect which could be your starting point:

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func call(f interface{}, args []interface{}) {
        // Convert arguments to reflect.Value
        vs := make([]reflect.Value, len(args))
        for n := range args {
            vs[n] = reflect.ValueOf(args[n])
        }
        // Call it. Note it panics if f is not callable or arguments don't match
        reflect.ValueOf(f).Call(vs)
    }
    
    func greet(n1, n2 string) {
        fmt.Printf("%s %s
    ", n1, n2)
    }
    
    func main() {
        l := []interface{}{"hello", "world"}
        call(greet, l)
    }
    
    // Output: hello world
    

    https://play.golang.org/p/vbi3CChCdV

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

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000