【发布时间】:2014-02-14 02:18:26
【问题描述】:
我在操场上有一些代码:sample code
我将一个二维字符串切片传递给一个函数 test,它可以接受可变参数,并且在 test() 中我可以获得第一个参数的基础类型,但是如何将它转换回它的基础类型?因为我必须迭代它的底层类型
我不喜欢这样硬编码:
if reflect.TypeOf(args[0]).String() == "[][]string" {
val := args[0].([][]string)
}
问题是如果我知道它的类型字符串是“[][]string”或别的什么,我怎样才能把它转换成类型?
我把完整的代码贴在这里,并添加一些cmets:
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)
}
【问题讨论】:
-
这看起来像一个“A B 问题”。你能解释一下你打算用你的代码做什么吗?
-
你确定你真的需要反射并且无法摆脱类型断言/切换吗?
标签: reflection interface go slice