duration := 1 * time.Hour
if true {
duration, err := time.ParseDuration("5s")
_ = duration // if I don't have this, it gives me a duration declared not used error
if err != nil {
log.Fatal(err)
}
}
fmt.Println(duration) // prints 1 hour
I guess the issue here is that duration is declared again as local var within if statement. Is there a syntactically good way to resolve this?
Indeed, you declare the duration variable again in the if block. My way to do this is to declare err before the if block (usually at the beginning of the function, as an error variable is pretty much always needed...).
var err error
duration := 1 * time.Hour
if true {
duration, err = time.ParseDuration("5s")
if err != nil {
log.Fatal(err)
}
}
The question is whether you want duration to be overwritten when time.ParseDuration returns an error or not. If not, then I would write
duration := 1 * time.Hour
if true {
d, err := time.ParseDuration("5s")
if err != nil {
log.Fatal(err)
} else {
duration = d
}
}
If you don't care about the old value in the case of an error, @julienc's answer is just as good.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With