Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go variable doesn't get overwritten in if statement

Tags:

go

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?

like image 508
Zeyang Avatar asked Mar 12 '26 06:03

Zeyang


2 Answers

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)
    }
}
like image 77
julienc Avatar answered Mar 15 '26 01:03

julienc


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.

like image 32
Fred Foo Avatar answered Mar 15 '26 03:03

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!