If I use a variable declaration into if
, I get an error undefined: completeTime
if completeTime, err := time.Parse(time.RFC3339Nano, "2016-06-06 18:11:24.617Z"); err != nil {
return
}
fmt.Println(time.Since(completeTime).Seconds())
But if I declaration that, I get an error completeTime declared and not used
var completeTime time.Time
if completeTime, err := time.Parse(time.RFC3339Nano, "2016-06-06 18:11:24.617Z"); err != nil {
return
}
fmt.Println(time.Since(completeTime).Seconds())
Why and how to do it right?
You have a scope problem in your code:
if completeTime, err := time.Parse(time.RFC3339Nano, "2016-06-06 18:11:24.617Z"); err != nil {
return
}
fmt.Println(time.Since(completeTime).Seconds())
In this sample, completeTime
is defined only for local scope inside the if
statement, which means you cannot use it outside it.
var completeTime time.Time
if completeTime, err := time.Parse(time.RFC3339Nano, "2016-06-06 18:11:24.617Z"); err != nil {
return
}
fmt.Println(time.Since(completeTime).Seconds())
This one is a bit more tricky. You define a completeTime
var with the correct scope at the beginning. Then, because of the :=
operator, you define another completeTime
inside the if
statement, which masks the first one.
Also, this second variable is not used, that's why you get the error. You can fix this problem by simply assigning completeTime
and err
outside the if
:
completeTime, err := time.Parse(time.RFC3339Nano, "2016-06-06 18:11:24.617Z")
if err != nil {
return
}
fmt.Println(time.Since(completeTime).Seconds())
You need to declare it (as you found out) before the if. The scope of the variable in your example is limited to the "if" block. Sorry if it doesn't look nice, but that how it be. Please note your second example requires an additional change (note the change in := on the beginning of your if line):
var completeTime time.Time
var err error
if completeTime, err = time.Parse(time.RFC3339Nano, "2016-06-06 18:11:24.617Z"); err != nil {
return
}
fmt.Println(time.Since(completeTime).Seconds())
As others have said, variables inside a block are not promoted to the outside of the block. But you can use the declared variables in else
and else if
statements.
For example (on play):
func main() {
if completeTime, err := time.Parse(time.RFC3339Nano, "2016-06-06 18:11:24.617Z"); err != nil {
fmt.Println(err)
} else {
fmt.Println(time.Since(completeTime).Seconds())
}
}
You can read more about blocks and scopes in the specification.