Always a new variable when multiople returns

blov · · 349 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;m facing a wierd problem with Golang.</p> <p>On <code>init()</code> function, i want to assign a value to my variable that was declared outside this function.</p> <p>But to assign the value to this var, i need to get <code>error</code> to check if everything is ok.</p> <p>Here is the code:</p> <pre><code>var retryValue time.Duration func init() { retryValue, err := time.ParseDuration(retries) if err != nil { log.Fatal(&#34;retries value is invalid&#34;, err) } } func a(){ fmt.Println(retryValue) } </code></pre> <p>And i get the compiling error: <code>retryValue declared and not used</code></p> <p>I need to change <code>init()</code> to this:</p> <pre><code>func init() { var err error retryValue, err = time.ParseDuration(retries) if err != nil { log.Fatal(&#34;retries value is invalid&#34;, err) } } </code></pre> <p>There is another way to solve this problem? <code>:=</code> always create a new variable if one of the variables are already declared? It&#39;s about variable golang&#39;s sope?</p> <p>Thanks!</p> <hr/>**评论:**<br/><br/>shovelpost: <pre><p>It is generally a good practice to <a href="https://peter.bourgon.org/blog/2017/06/09/theory-of-modern-go.html" rel="nofollow">avoid init</a> and pass your dependencies explicitly. </p></pre>forfunc: <pre><p>In your example you are shadowing the retryValue variable. The ones in init belongs to the scope in the init function. As you already mentioned, the solution to this is changing it by declaring the error up front and using <code>=</code> instead of <code>:=</code>.</p></pre>tiagopotencia: <pre><p>Thank, bro! I&#39;m looking for a more elegant solution for this! :)</p></pre>forfunc: <pre><p>I&#39;m not sure how your program looks but using init functions seems a bit weird to me. It is better to avoid using global variables and to do this kind of parsing in your main function and then passing it on as a parameter to the <code>a</code> function.</p></pre>Morgahl: <pre><p>His answer pretty much is the cleanest way aside from <code>Must</code> take a look at the <code>text/tenplate</code> or <code>html/template</code> packages. </p></pre>

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

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