go-可变参数

今天在尝试用go写一个简单的orm的时候 发现 在调用可变参数函数时,不是总能使用省略号将一个切片展开,有时候编译器可能会报错 再此用几个简单的例子作为说明

当不太确定数据类型的时候我们通常采用空接口

tests1(789)
fmt.Println("-------------")
tests1("789")
func tests1(arg interface{}) {
    fmt.Println("value:",arg)
    fmt.Println("type:",reflect.TypeOf(arg).Name())
}

输出结果

value: 789
type: int
-------------
value: 789
type: string

在使用相同类型的可变入参时

tests([]string{"4","5","6"}...)
func tests(args ...string) {
    for i,v := range args {
        fmt.Println(i,"----",v)
    }
}

输出结果

0 ---- 4
1 ---- 5
2 ---- 6

当使用interface{}作为可变入参时

func testParams(args ...interface{}) {
    for i,v := range args {
        if s,ok := v.(string); ok {
            fmt.Println("----",s)
        }
        if s,ok := v.([]string); ok {
            for i,v := range s {
                fmt.Println(i,"[]----",v)
            }
        }
        fmt.Println(i,v)
    }
}

出现错误

cannot use []string literal (type []string) as type []interface {} in argument to testParams

当看到这里时候答案已经露出水面了
这里提供两种解决方案

第一种方法

s := []string{"4","6"}
var d []interface{} = []interface{}{s[0],s[1],s[2]}
testParams(d...)

结果

---- 4
0 4
---- 5
1 5
---- 6
2 6

第二种方法

s := []string{"4","6"}
var d []interface{}
d = append(d,s)
testParams(d...)

结果

0 []---- 4
1 []---- 5
2 []---- 6
0 [4 5 6]

总结: 在使用interface{}作为可变入参时 传入的参数要做类型转换

相关文章

类型转换 1、int转string 2、string转int 3、string转float ...
package main import s "strings" import...
类使用:实现一个people中有一个sayhi的方法调用功能,代码如...
html代码: beego代码:
1、读取文件信息: 2、读取文件夹下的所有文件: 3、写入文件...
配置环境:Windows7+推荐IDE:LiteIDEGO下载地址:http:...