Linter for checking named returns?

agolangf · · 732 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Is there a command line tool, check, or flag to warn when Go code uses named returns? I&#39;d like a CI-friendly way to discourage named returns, as they interact poorly with scoping, causing surprising variable assignments.</p> <hr/>**评论:**<br/><br/>epiris: <pre><p>How do they interact poorly with scoping? They identifiers are bound to the function body which is just a block, they then behave like any other vardecl. Meaning these two have identical scoping semantics:</p> <pre><code>// func() (n int, err error) // ^ behaves like below { var (n int; err error); } </code></pre></pre>mcandre: <pre><p>To be more specific, named returns interact in surprising ways with shadowing:</p> <p><a href="!topic/golang-nuts/VeJTB9dhhK4" rel="nofollow">!topic/golang-nuts/VeJTB9dhhK4</a></p></pre>epiris: <pre><p>Being a named return value doesn&#39;t have anything to do with that though. Go is following scoping rules when declaring a variable in a new block, the topics <a href="" rel="nofollow">example</a> is identical to <a href="" rel="nofollow">var declaration</a>. The fact it&#39;s declared in a different location may make it seem more confusing, but remove it and all you did is move your surprise down a line. </p></pre>dlsniper: <pre><p>As Go explicitly allows for named returns, aside for particular use-cases like yours, there wouldn&#39;t be much value in having those functions / methods reported.</p> <p>You can create your own linter, if you so desire, have a look at: <a href="" rel="nofollow"></a> for inspiration on how to use the Go packages from go/* to solve this.</p> <p>Edit: However I&#39;d recommend using megacheck, from that toolbox, to detect whenever something&#39;s wrong with your code and then you can safely use named returns.</p></pre>dlsniper: <pre><p>I&#39;ve forgot to mention, having named return values can be invaluable when returning multiple values of the same type. It increases the readability by 100x easily. </p></pre>ChristophBerger: <pre><p>I fully agree - if, at the same time, naked return statements are avoided.</p></pre>dlsniper: <pre><p>Yup. Naked returns are good for 5-8 lines of code, after that it&#39;s probably better to explicitly return. Iirc, this was one of the code review recommendations.</p></pre>

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

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