Is there a more idiomatic way to create closure functions on init

xuanbao · · 446 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi guys, i&#39;m making a lexer/parser to interpret natural language. it&#39;s based loosely on Rob Pike&#39;s state machine talk. <a href="https://www.youtube.com/watch?v=HxaD_trXwRE" rel="nofollow">https://www.youtube.com/watch?v=HxaD_trXwRE</a> But my state functions are closures with all the possible state functions that they can return stored in a map. (non compiling example): <a href="https://play.golang.org/p/1F5mGeSdh_" rel="nofollow">https://play.golang.org/p/1F5mGeSdh_</a> I chose this way because i wanted a solution that was quick even at scale and a map is very quick for looking up key-&gt;val. I didn&#39;t use globals because some-one could write to a global and corrupt data. But I didn&#39;t want to allocate a new map every time I lex input, so i went with closure functions and a init function for every closure. This way the functions are available on the global scope.</p> <p>So I think it&#39;s an elegant solution for the problem, but it doesn&#39;t read very easily. Is there a more readable, or idiomatic way to do the same thing?</p> <p>Your help is greatly appreciated Cheers, Mario</p> <hr/>**评论:**<br/><br/>Fwippy: <pre><p>You can just use a &#34;global&#34; map. Really, it&#39;s package-level, as it lives under <code>yourpkg.keyWords</code>.</p> <p>And if you don&#39;t Uppercase the first letter, it won&#39;t be exported / visible to anyone who uses your library, so the only person who can read/write to it is you.</p></pre>itsamemmario: <pre><p>Hey man, thanks for the input. It might come out a lot cleaner that way. The reason i chose to put it in closures is because my code would have to be worked on with a team afterwards(i hope). It&#39;s just the basic setup. I&#39;m trying to make it hard to use the package wrongly by designing the code in a way that the &#34;global&#34; variables can&#39;t be accessed on the global scope. and don&#39;t have to be re-allocated. Also every stateFn holds a slightly different map, since certain keywords need different state functions in different contexts. And the ability to be able to pass the wrong map to a stateFn seems dangerous.</p> <p>Although i&#39;ve never used this approach before, it might lead to messy code down the road. But my hope is less messy code than straight-up globals.</p></pre>

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

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