Question: Converting interface to struct

blov · · 2089 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>The following code doesn&#39;t convert: <a href="http://play.golang.org/p/8kWAndjG9Z">http://play.golang.org/p/8kWAndjG9Z</a></p> <p>My main objective is to make a lots of structs with similar definitions to use a specific function using the power of interfaces. MyTestStruct.Data can be typed anything including int, string, []string, struct etc.</p> <hr/>**评论:**<br/><br/>rco8786: <pre><p>It looks like you&#39;re trying to fake generics.</p> <p>In general though, you&#39;re trying to cast an anonymous struct with the signature <code>Id int, Data interface</code> to a named struct with the signature <code>Id int, Data []string</code>. I&#39;m not sure why you&#39;d expect that to work.</p></pre>QThellimist: <pre><p>This works <a href="http://play.golang.org/p/HtD2OKViJ6" rel="nofollow">http://play.golang.org/p/HtD2OKViJ6</a><br/> This doesn&#39;t work <a href="http://play.golang.org/p/JZAQjEb8il" rel="nofollow">http://play.golang.org/p/JZAQjEb8il</a> (I changed the type from []string to interface{})</p> <p>Conversion between struct to struct doesn&#39;t work including casting to interface{}. Maybe there is a work around.</p></pre>rco8786: <pre><p>Because you&#39;re casting from interface{} to interface{}. </p></pre>barsonme: <pre><p>It works because they&#39;re all pointers to type <code>T</code></p> <p>In your other example you have two fundamentally different types:</p> <pre><code>type foo struct { A int; B []string } bar := foo{ A: 21, B: []string{&#34;Hello, world!&#34;}, } </code></pre> <p>and</p> <pre><code>baz := struct { A int B interface{} } { A: 21, B: []string{&#34;Hello, world!&#34;}, } </code></pre></pre>QThellimist: <pre><p>True. Is there a work around you can think of?</p></pre>jerf: <pre><p>No. Go is neither covariant nor contravariant. Types are either equal or they aren&#39;t.</p> <p>You have to either take the structs apart and deal with the pieces, or use reflection. Type assertions are only &#34;assertions&#34;, not &#34;coercions&#34; of any kind.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

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