<p>I'm trying to figure out how to replace an explicit creation of a typed object with a type that's contained in an interface at runtime.</p>
<p>if I create it EXPLICITLY it works. If I IMPLICITLY create the object it panics.</p>
<p>Here's the code below:</p>
<pre><code>package main
import (
"fmt"
"reflect"
)
func main() {
myData := make(map[string]interface{})
myData["name"] = "bob"
myData["age"] = 25
result := &MyStruct{}
FillStruct(myData, result)
fmt.Printf("%s is %d\n", result.Name, result.Age)
}
func FillStruct(data map[string]interface{}, result interface{}) {
t := reflect.ValueOf(result).Elem()
typ := t.Type()
fmt.Printf("interface is of type [%s]\n", typ.Name())
// EXPLICIT creation of struct --works
ms := MyStruct{}
// IMPLICIT creation of struct -- fails
ms:=reflect.New(reflect.ValueOf(result).Type()).Elem()
fmt.Printf("created a [%T]\n", reflect.ValueOf(ms).Type())
st := reflect.TypeOf(ms)
fmt.Printf("%d fields\n", st.NumField())
fmt.Printf("[%s] [%s]\n", st.Name(), reflect.TypeOf(ms).Name())
for i := 0; i < st.NumField(); i++ {
field := st.Field(i)
json := field.Tag.Get("json")
name := field.Name
fmt.Printf("json [%s] field [%s]\n", json, name)
val := t.FieldByName(field.Name)
val.Set(reflect.ValueOf(data[json]))
}
}
type MyStruct struct {
Name string `json:"name" binding:required`
Age int `json:"age"`
}
</code></pre>
<hr/>**评论:**<br/><br/>pierrrre: <pre><p>With fmt.Printf("type of ms: %T\n", ms) you can check the type of ms.</p>
<p>ms := MyStruct{}</p>
<p>type of ms: main.MyStruct</p>
<p>ms := reflect.New(reflect.ValueOf(result).Type()).Elem()</p>
<p>type of ms: reflect.Value</p></pre>Rabarar: <pre><p>Not sure I see your point. You can see that I've printed out the type of each object in the code...</p>
<p>The question is how to create an equivalent type to an explicit declaration. </p></pre>Rabarar: <pre><p>SOLVED!</p>
<p>It turns out that the magic sauce to create an instance at runtime looks like this:</p>
<pre><code>t := reflect.ValueOf(result).Elem()
typ := t.Type()
ms:=(reflect.New(typ).Elem()).Interface()
</code></pre></pre>Logiraptorr: <pre><p>Just to clarify, It's more direct to use TypeOf instead of ValueOf.</p>
<pre><code>t := reflect.TypeOf(result).Elem()
ms := reflect.New(t).Elem().Interface()
</code></pre></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传