<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>
