Please help with Dynamically Unmarshaling yaml in golang

xuanbao · · 334 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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>&amp;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&#39;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&#39;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&#39;s not easily explained, I&#39;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

334 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传