Var declaration in the middle of the code

xuanbao · · 541 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>What are your thoughts about declaring variables in the middle of the code, right before the line they are called at vs. in the beginning but far from where they are used?</p> <p>The concrete use case is a 300+ lines main func, where the channels are declared around line 200 with names of the format:</p> <pre><code>chActivity chan&lt;- []byte </code></pre> <p>I looked up for similar questions here, found these that are related, but not answering my question:</p> <ul> <li><a href="https://www.reddit.com/r/golang/comments/84qfe1/var_style_to_group_or_not_to_group_that_is_the/" rel="nofollow">Group or not group</a></li> <li><a href="https://www.reddit.com/r/golang/comments/1045a7/question_about_declaring_variables_in_go/" rel="nofollow">Var declaration inside funcs</a></li> </ul> <hr/>**评论:**<br/><br/>sh41: <pre><blockquote> <p>What are your thoughts about declaring variables in the middle of the code, right before the line they are called</p> </blockquote> <p>Generally, this would be my preference. Why declare something further away from where it&#39;s actually needed and used?</p></pre>adiabatic: <pre><p>I prefer to keep them closer to where they&#39;re first used (C++ style), not all at the top of the function (C89 style).</p></pre>nastus: <pre><p>I&#39;d think you would mostly be doing it at preference. Ultimately I try to keep things in position relative to the scope, makes it much easier to maintain</p></pre>SeweragesOfTheMind: <pre><p>Your best bet is to break down that main function into smaller ones so that this is a non-issue. 300 lines is.... excessive. And probably untestable.</p></pre>HarwellDekatron: <pre><p>I feel it&#39;s more idiomatic to declare the variables closer to the use. I&#39;ve read and written a significant amount of Go code and only in very rare occasions even use the &#34;var&#34; keyword inside of a function (usually before an <code>if</code> statement that&#39;ll define the value). Putting the variable declarations at the top of the function&#39;s body would look like old C code.</p> <p>Also, having a 300+ line main function sounds like a bad idea anyway.</p></pre>moneygame7373: <pre><p>Generally var are declared on top along with any other types and then following that functions , receiver methods. But if the file is long enough it would be better to declare it closer. How I would do it is to see if your file is trying to implement different logic in the same file. Then all the relevant variables that are going to be used to implement that particular logic are kept in the same area. Makes your code easy to read and maintain</p></pre>

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

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