構造体があり、そのキーを取得したいのですが、現在はタイプの場合、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()
などを呼び出す必要がありますか?もっとエレガントな方法があるといいのですが。
これは可能です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
}
(+さらにいくつかのエラー処理)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加