The Initial Statement of an If Block

An if conditional can have an "initial" statement. The variable(s) created in the initial statement are only defined within the scope of the if body.

if INITIAL_STATEMENT; CONDITION {
}

Why Would I Use This?

It has two valuable purposes:

  • It's a bit shorter

  • It limits the scope of the initialized variable(s) to the if block

For example, instead of writing:

without-initial-statement.go
length := getLength(email)
if length < 1 {
    fmt.Println("Email is invalid")
}

We can do:

with-initial-statement.go
if length := getLength(email); length < 1 {
    fmt.Println("Email is invalid")
}

In the example above, length isn't available in the parent scope, which is useful because we don't need it there β€” it prevents accidental use elsewhere in the function.