gpt4 book ai didi

reflection - reflect.Value 的字符串方法无法按预期工作

转载 作者:IT王子 更新时间:2023-10-29 01:52:39 27 4
gpt4 key购买 nike

我正在尝试从 reflect.Value 中检索字符串值,

我希望 value.String()成为okok但我得到了<interface {} Value>相反。

我错过了什么吗?

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)
}

最佳答案

documentation for Value.String解释行为:

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 只是 fmt.Stringer 接口(interface)的一个实现。

如果你想要这个值本身,你可以使用 Interface function在 reflect.Value 上,然后进行类型断言以获取字符串。示例:

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)
}

Playground link

关于reflection - reflect.Value 的字符串方法无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36953337/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com