为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

交互式爱情 2021-11-29 15:47:14
我正在寻找一种优雅的方式来解压缩 Go 中的参数列表。我不想为此目的使用可变参数函数,因为在我的用例中,在编写函数时我已经知道参数的数量,我想保持这部分简单。但是在我的用例中,参数以[]interface{}. 我找不到解决方案,但嘿,也许有人已经知道如何做到这一点?package mainimport (    "fmt")// NON-VARIADIC greaterfunc 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?}
查看完整描述

2 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

您可以使用反射包创建一个“通用”调用者,尽管这会带来开销并且缺乏类型安全性。除非您有一些特殊情况并且不知道您想在代码中调用什么,否则使用您的问题中的代码片段会更明智,但您认为这并不优雅。


反射的示例用法可能是您的起点:


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\n", n1, n2)

}


func main() {

    l := []interface{}{"hello", "world"}

    call(greet, l)

}


// Output: hello world

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


查看完整回答
反对 回复 2021-11-29
?
MM们

TA贡献1886条经验 获得超2个赞

我不太确定你要做什么。如果您想要一种方法轻松地将两个空接口的一部分传递给接受两个字符串的函数,您可以创建一个小助手:


func twoStrings(vs []interface{}) (string, string) {

    return vs[0].(string), vs[1].(string)

}

将其用作


greet(twoStrings(l))

游乐场:http : //play.golang.org/p/R8KFwMUT_V。


但老实说,你似乎做错了什么,试图让 Go 类型系统做一些它不能做的事情。


查看完整回答
反对 回复 2021-11-29
  • 2 回答
  • 0 关注
  • 206 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信