<p>I asked a similar question here earlier in the week. The answer moved me away from solution in that question to the one in the StackOverflow post. I believe this is a truly common and problematic issue with Golang, but I am unable to find a solution to it in Google. Please see what you can do. Hopefully the community can solve this problem in a DRY way.</p>
<p>Thank you.</p>
<p><a href="https://stackoverflow.com/questions/47827043/dynamically-unmarshaling-yaml-in-golang" rel="nofollow">https://stackoverflow.com/questions/47827043/dynamically-unmarshaling-yaml-in-golang</a></p>
<hr/>**评论:**<br/><br/>TheMerovius: <pre><p>The solution, I believe, is to simply pass <code>t</code>, not <code>&t</code> to Unmarshal.</p>
<p>Rationale: You need to pass a pointer to a struct which can take the intended data as a dynamic value in the <code>interface{}</code> to Unmarshal. From <code>pickT</code>, you return <code>new(Collection)</code>, which is such a pointer. But then, you first store it in another interface type (Migration) and then take the pointer <em>of that</em>. Meaning, yaml will a) see that it gets passed a pointer and b) try to store the value in the pointee. But the pointee is of interface type (and <em>that</em> interface value will then contain the actual struct, but yaml doesn't do this additional redirection).</p>
<p>If you instead pass <code>t</code> (which has interface type) it will first be converted to <code>interface{}</code> and then passed on - so the argument will directly contain a <code>*Collection</code>, as intended.</p>
<p>The difference here is, that if you convert/assign one interface type to another, it won't get re-wrapped, but the dynamic value in one value will just be transferred to another. But if you store a non-interface type (like a <em>pointer</em> to an interface), it will get re-wrapped.</p>
<p>It's not easily explained, I'm afraid. You can see the effect here too: <a href="https://play.golang.org/p/ia181c_Pwp" rel="nofollow">https://play.golang.org/p/ia181c_Pwp</a> (note, that Printf also takes an <code>interface{}</code>)</p></pre>VirmundiUndead: <pre><p>You won the Internet Golang problem of the day. That did indeed work. I could have sworn I had that. Thank you.</p>
<p>Please go to StackOverflow and collect your Internet points there too.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传