I have some code in the playground: sample code
I pass a two dimension string slice into a function test, which can accept variadic arguments, and in test() I can get the first argument's underlying type, but how can I convert it back to its underlying type? because I have to iterate on its underlying type
I don't like to hard code it like:
if reflect.TypeOf(args[0]).String() == "[][]string" { val := args[0].([][]string) } the question is if I know its type string is "[][]string" or something else, how can I convert it to the type?
I post the full code here, and add some comments:
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) }