<p>Is there a command line tool, check, or flag to warn when Go code uses named returns? I'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="https://groups.google.com/forum/m/#!topic/golang-nuts/VeJTB9dhhK4" rel="nofollow">https://groups.google.com/forum/m/#!topic/golang-nuts/VeJTB9dhhK4</a></p></pre>epiris: <pre><p>Being a named return value doesn'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="https://play.golang.org/p/SsdRsjYj1G" rel="nofollow">example</a> is identical to <a href="https://play.golang.org/p/KmE1BqRczo" rel="nofollow">var declaration</a>. The fact it'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'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="https://github.com/dominikh/go-tools" rel="nofollow">https://github.com/dominikh/go-tools</a> for inspiration on how to use the Go packages from go/* to solve this.</p>
<p>Edit: However I'd recommend using megacheck, from that toolbox, to detect whenever something's wrong with your code and then you can safely use named returns.</p></pre>dlsniper: <pre><p>I'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's probably better to explicitly return. Iirc, this was one of the code review recommendations.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传