如何在未知接口上获得结构值{}

时间:2012-12-13 09:15:50

标签: interface struct go

如果我有一个结构,我想得到它的关键,但它目前的类型interface{}我该怎么做?

目前我收到以下编译错误:

invalid operation: d[label] (index of type interface {})

播放:http://play.golang.org/p/PLr91d55GX

package main

import "fmt"
import "reflect"

type Test struct {
    s string
}

func main() {
    test := Test{s: "blah"}
    fmt.Println(getProp(test, "s"))
}

func getProp(d interface{}, label string) (interface{}, bool) {
    switch reflect.TypeOf(d).Kind() {
    case reflect.Struct:
        _, ok := reflect.TypeOf(d).FieldByName(label)
        if ok {
                    // errors here because interface{} doesn't have index of type 
            return d[label], true
        } else {
            return nil, false
        }
    }
}

我是否真的必须对每种不同的类型执行大量的case语句并调用反映的reflect.ValueOf(x).String()等?我希望有更优雅的方式。

2 个答案:

答案 0 :(得分:2)

你可以这样做,但我认为只有你的结构成员s是一个导出的字段(例如在你的例子中使用大写S)才会有效。

func getProp(d interface{}, label string) (interface{}, bool) {
    switch reflect.TypeOf(d).Kind() {
    case reflect.Struct:
        v := reflect.ValueOf(d).FieldByName(label)
             return v.Interface(), true
    }
   return nil, false
}

(+更多错误处理)

答案 1 :(得分:0)

我不确定您正在寻找什么,但有一种稍微简单的方法来查找接口{}类型。在您的情况下,您可以使用:

switch val := d.(type) {
  case Test:
    fmt.Println(d.s)
}

显然,我没有做与你相同的事情,但我的想法是你可以用" d。(类型)"来检查类型,一次"案例测试:"确定它是Test类型的结构,您可以这样访问它。

不幸的是,这并没有解决标签对结构中值的访问,但它至少是一种更优雅的方式来确定类型,@ nos显示如何使用

v := reflect.ValueOf(d).FieldByName(label)
return v.Interface(), true
相关问题