英文:
golang: accessing value in slice of interfaces
问题
我有一个数据结构,通过 go-spew 输出的样子如下:
([]interface {}) (len=1 cap=1) {
(string) (len=1938) "value"
}
它的类型是 []interface {}
我该如何使用 fmt 打印这个 value,或以某种方式访问它,以便我可以使用它。
英文:
I have a data structure which comes of out go-spew looking like this:
([]interface {}) (len=1 cap=1) {
 (string) (len=1938) "value"
}
It is of type []interface {}
How can I print this value with fmt, or access it in some way so that I can use it.
答案1
得分: 1
你可以使用类型断言或反射来处理泛型的interface{}类型的底层类型。具体如何操作取决于你的特定用例。如果你可以预期interface{}是一个[]interface{},就像你的示例中一样,你可以这样做:
if sl, ok := thing.([]interface{}); ok {
    for _, val := range sl {
        fmt.Println(val)
        // 或者如果需要的话,将val强制转换为其底层类型,例如 strVal := val.(string)
    }
}
如果你无法对底层类型做出假设,你将需要使用reflect进行一些黑魔法操作。
英文:
You can use type assertions or reflection work with the generic interface{} to an underlying type. How you do this depends on your particular use case. If you can expect the interface{} to be a []interface{} as in your example, you can:
if sl, ok := thing.([]interface{}); ok {
	for _, val := range sl {
		fmt.Println(val)
        // Or if needed, coerce val to its underlying type, e.g. strVal := val.(string)
	}
}
If you can't make assumptions about the underlying type, you'll need to do some black magic using reflect.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论