What's the best way to handle inferred variable in an if statement?

blov · · 347 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>for example, I want to assign the variable only the condition met</p> <pre><code>if cond { foo := func } // use foo, but it&#39;s out of scope </code></pre> <hr/>**评论:**<br/><br/>_jenni4: <pre><p>In most cases you can think of curly braces as &#34;define a separate scope, here.&#34;</p> <p>Information from nested scopes can&#39;t be accessed by enclosing scopes, but can go the other way.</p> <p>Example: <a href="https://play.golang.org/p/B9eEPyveK0h" rel="nofollow">https://play.golang.org/p/B9eEPyveK0h</a></p></pre>sharptoothy: <pre><p>Perhaps I just don&#39;t get something but why not just say:</p> <pre><code>if cond { v := someFunc() // use v here } // don&#39;t use v here </code></pre> <p>Unless v was already defined somewhere else and just might need to be updated:</p> <pre><code>func (o obj) getValue(a int) int { if o.needsUpdate() { a = o.updatedInt() } return o.doSomething(a) } </code></pre> <p>Or you&#39;re doing something like what 014a said where in an else branch, you want to set the value to something else. Is there some other situation?</p></pre>014a: <pre><p>I write code with this general logic quite often.</p> <pre><code>if cond { foo = Thing() } else { foo = OtherThing() } </code></pre> <p>The easiest way to accomplish this similarly in Go is to define the variable before the branches</p> <pre><code>var foo Bar if cond { ... </code></pre> <p>It works and is a good pattern. The other thing you can do, which might be cleaner depending on your specific logic, is to use an anonymous function:</p> <pre><code>foo := func() Bar { if cond { return Thing() } else { return OtherThing() } }() </code></pre> <p>And depending on the size of each branch you may want to break that out into its own separate function.</p></pre>hell_0n_wheel: <pre><blockquote> <p>use an anonymous function:</p> </blockquote> <p>Especially if you need to populate the value from an external source. I use this pattern often:</p> <pre><code>err := func(*s SomeType) error { c := NewClient(dbconn) defer c.Close() s, err := c.Get() return err }() </code></pre> <p>The anon function traps the scope of the defer statement, so you can use multiple clients in the same method... if that&#39;s your cuppa tea.</p></pre>a_t-2: <pre><pre><code> var foo type if cond { foo = value } // use foo </code></pre> <p>A language has rules, you can&#39;t just make up new ones because you don&#39;t like them.</p></pre>

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

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