<p>I'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("retries value is invalid", 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("retries value is invalid", 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's about variable golang'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'm looking for a more elegant solution for this! :)</p></pre>forfunc: <pre><p>I'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
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传