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

我正在寻找一种优雅的方式来解压缩 Go 中的参数列表。我不想为此目的使用可变参数函数,因为在我的用例中,在编写函数时我已经知道参数的数量,我想保持这部分简单。但是在我的用例中,参数以[]interface{}. 我找不到解决方案,但嘿,也许有人已经知道如何做到这一点?


package main


import (

    "fmt"

)


// NON-VARIADIC greater

func greet(n1, n2 string) {

    fmt.Printf("%s %s\n", 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?

}


交互式爱情
浏览 207回答 2
2回答

幕布斯7119047

您可以使用反射包创建一个“通用”调用者,尽管这会带来开销并且缺乏类型安全性。除非您有一些特殊情况并且不知道您想在代码中调用什么,否则使用您的问题中的代码片段会更明智,但您认为这并不优雅。反射的示例用法可能是您的起点:package mainimport (    "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\n", n1, n2)}func main() {    l := []interface{}{"hello", "world"}    call(greet, l)}// Output: hello worldhttps://play.golang.org/p/vbi3CChCdV

MM们

我不太确定你要做什么。如果您想要一种方法轻松地将两个空接口的一部分传递给接受两个字符串的函数,您可以创建一个小助手:func twoStrings(vs []interface{}) (string, string) {    return vs[0].(string), vs[1].(string)}将其用作greet(twoStrings(l))游乐场:http : //play.golang.org/p/R8KFwMUT_V。但老实说,你似乎做错了什么,试图让 Go 类型系统做一些它不能做的事情。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python