我将一个二维字符串切片传递到一个函数 test 中,该函数可以接受可变参数,并且在 test() 中我可以获得第一个参数的基础类型,但是如何将其转换回其基础类型?因为我必须迭代它的底层类型
我不喜欢硬编码它:
if reflect.TypeOf(args[0]).String() == "[][]string" {
val := args[0].([][]string)
}
问题是如果我知道它的类型字符串是“[][]string”或其他东西,我该如何将其转换为类型?
我在这里发布了完整的代码,并添加了一些注释:
package main
import (
"reflect"
"fmt"
)
func test(args ...interface{}) {
fmt.Println("type", reflect.TypeOf(args[0]))
// here will be a compile error, because args[0]'type now is interface{},
// not a slice, though it's underlying type is slice
for i, v := range args[0] {
}
// so, how could I convert args[0] to [][]string when I get its type
// string "[][]string" ?
// I know use type assertion is possible, but you must guess the possible
// type the args[0] will be.
// is there a way to do it from a type's string representation to the
// actual type?
// so I can write code like this:
// val := args[0].(reflect.TypeOf(args[0]).String()), which is very general
}
func main() {
arr := [][]string{{"asd", "sd", "rt"}, {"34","gf","gf"}}
test(arr)
}
繁华开满天机
相关分类