golang: accessing value in slice of interfaces

huangapple go评论88阅读模式
英文:

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

Playground链接

如果你无法对底层类型做出假设,你将需要使用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)
	}
}

(Playground link)

If you can't make assumptions about the underlying type, you'll need to do some black magic using reflect.

huangapple
  • 本文由 发表于 2017年7月7日 00:19:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/44954218.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定