<p>I spent all day reading docs and gobyexample.com and so on, and I haven't seen anything that feels like it will solve my problem. Basically, I have a situation like this:</p>
<pre><code>type Cat struct {
name string
}
type Dog struct {
name string
}
type Person struct {
name string
}
func GetEntity(foo int) CatDogPerson{} {
switch (foo) {
case 1:
return Cat{"Mao"}
case 2:
return Dog{"Fido"}
case 3:
return Person{"Dave"}
}
}
</code></pre>
<p>Is there a way for GetEntity() to return one of those three structs? Or do I have to return multiple, like:</p>
<pre><code>func GetEntity(foo int) (*Cat{}, *Dog{}, *Person{}) {
...
}
</code></pre>
<p>And if that's how you do it, how can I distill the one that was returned down to one item later, so that I can do something like <code>name := result.name</code>? </p>
<p>Is that even possible in Go, or am I overthinking this?</p>
<p>Thanks in advance.</p>
<hr/>**评论:**<br/><br/>kl0nos: <pre><p>Use interface</p>
<p><a href="https://golang.org/doc/effective_go.html#interfaces_and_types">https://golang.org/doc/effective_go.html#interfaces_and_types</a></p></pre>Fwippy: <pre><p>Yep, interfaces are the way to do this. Here's an example, modified from the original code: <a href="https://play.golang.org/p/1UmP9lknUX">https://play.golang.org/p/1UmP9lknUX</a></p></pre>jeffrallen: <pre><p>Here's an example of how to use %T, which I find useful when debugging code like this:
<a href="https://play.golang.org/p/79jNCAG4cm" rel="nofollow">https://play.golang.org/p/79jNCAG4cm</a></p></pre>FourSigma: <pre><p>Interfaces are great for this situation. You can do a type assertion for Cat, Dog, or Person.
<a href="https://play.golang.org/p/bRShJ4O-zo" rel="nofollow">https://play.golang.org/p/bRShJ4O-zo</a></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传