Reflection.Value的字符串方法无法按预期工作
问题描述:
I'm trying to retrieve the string value from a reflect.Value,
I expect value.String()
to be okok
but I got <interface {} Value>
instead.
Did I miss something?
package main
import (
"fmt"
"reflect"
)
func dump(args *[]interface{}) {
value := reflect.ValueOf(*args).Index(0)
fmt.Println(value.String())
if value.String() != "okok" {
fmt.Println("miss")
}
}
func main () {
var args []interface{}
args = append(args, "okok")
dump(&args)
}
答
The documentation for Value.String explains the behavior:
Unlike the other getters, it does not panic if v's Kind is not String. Instead, it returns a string of the form "<T value>" where T is v's type.
String is just an implementation of the fmt.Stringer interface.
If you want the value itself, you can use the Interface function on reflect.Value and then do a type assertion to get the string. Example:
package main
import (
"fmt"
"reflect"
)
func dump(args *[]interface{}) {
value := reflect.ValueOf(*args).Index(0)
str := value.Interface().(string)
fmt.Println(str)
if str != "okok" {
fmt.Println("miss")
}
}
func main() {
var args []interface{}
args = append(args, "okok")
dump(&args)
}