Instantiating different types depending on an input

polaris · · 431 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I want to create a mapping between strings and types, so an instance of a proper type is created depending on an input.</p> <p>Something like this, but obviously more scalable: <a href="https://play.golang.org/p/52TWcVMNyO" rel="nofollow">https://play.golang.org/p/52TWcVMNyO</a></p> <p>What is the idiomatic way of doing this?</p> <hr/>**评论:**<br/><br/>sleepydog: <pre><p>I am going to take your example as being close to what you want to do, because it&#39;s very hard to answer such a general question. I would create an interface that captures what information I actually want to use these various types for. For instance, we can derive lat/long from both named locations and coordinates, so I would make those two types implement the following interface:</p> <pre><code>type Location interface { Coord() (lat, long float32) } </code></pre> <p>and then your snippet in main() could go in a function, parseLocation, that returns a Location.</p> <p>If you want examples in the standard library, look for parsing code. For example, look at the types in the go/ast package and how they&#39;re returned from the go/parser package, or the Token type in the encoding/xml package.</p></pre>nsd433: <pre><p>I&#39;d use a <code>map[string]reflect.Type</code> and <code>reflect.New()</code> or <code>reflect.Zero()</code> to construct the types. However after that you have to set the fields, no? So to avoid needing more reflection, I&#39;d have each type implement an interface which takes the input arguments and parses them out.</p></pre>nsd433: <pre><p>Something like <a href="https://play.golang.org/p/k4Cf-Dx-_9" rel="nofollow">https://play.golang.org/p/k4Cf-Dx-_9</a></p></pre>jaksi7c8: <pre><blockquote> <p>However after that you have to set the fields, no?</p> </blockquote> <p>It&#39;s for parsing SSH requests, which is always done by <a href="https://godoc.org/golang.org/x/crypto/ssh#Unmarshal" rel="nofollow">ssh.Unmarshal</a>. It expects a variable of a struct type used to represent the value encoded in the payload. For example, a <code>pty-req</code> request includes the terminal type, width, height, while the <code>tcpip-forward</code> request includes a hostname and a port.</p></pre>nsd433: <pre><blockquote> <p>parsing SSH requests</p> </blockquote> <p>I see. So you have no need for anything beyond a reflect.New() of the proper type, which make things even simpler.</p></pre>whizack: <pre><p><a href="https://en.wikipedia.org/wiki/Abstract_factory_pattern" rel="nofollow">https://en.wikipedia.org/wiki/Abstract_factory_pattern</a></p></pre>

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

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