<p>The following code doesn'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're trying to fake generics.</p>
<p>In general though, you'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'm not sure why you'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'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't work including casting to interface{}. Maybe there is a work around.</p></pre>rco8786: <pre><p>Because you're casting from interface{} to interface{}. </p></pre>barsonme: <pre><p>It works because they'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{"Hello, world!"},
}
</code></pre>
<p>and</p>
<pre><code>baz := struct {
A int
B interface{}
} {
A: 21,
B: []string{"Hello, world!"},
}
</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't.</p>
<p>You have to either take the structs apart and deal with the pieces, or use reflection. Type assertions are only "assertions", not "coercions" of any kind.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传