golang_if

Golang if

Golang if

if

The if statement in Go is much like the if statement in most programming languages. Because it is such a familiar construct, I’ve used it in early sample code without worrying that it’d be confusing. Example 4-5 shows a more complete sample.

Example 4-5. if and else

n := rand.Intn(10) if n == 0 { fmt.Println(“That's too low”) } else if n > 5 { fmt.Println(“That's too big:”, n) } else { fmt.Println(“That's a good number:”, n) }

Note

If you run this code, you’ll find that it always assigns 1 to n. This happens because the default random number seed in math/rand is hard-coded. In “Overriding a Package’s Name”, we’ll look at a way to ensure a good seed for random number generation while demonstrating how to handle package name collisions.

The most visible difference between if statements in Go and other languages is that you don’t put parenthesis around the condition. But there’s another feature that Go adds to if statements that helps you better manage your variables.

As we discussed in the section on shadowing variables, any variable declared within the braces of an if or else statement exists only within that block. This isn’t that uncommon; it is true in most languages. What Go adds is the ability to declare variables that are scoped to the condition and to both the if and else blocks. Let’s take a look by rewriting our previous example to use this scope, as shown in Example 4-6.

Example 4-6. Scoping a variable to an if statement

if n := rand.Intn(10); n == 0 { fmt.Println(“That's too low”) } else if n > 5 { fmt.Println(“That's too big:”, n) } else { fmt.Println(“That's a good number:”, n) }

Having this special scope is very handy. It lets you create variables that are available only where they are needed. Once the series of if/else statements ends, n is undefined. You can test this by trying to run the code in Example 4-7 on The Go Playground.

Example 4-7. Out of scope…

if n := rand.Intn(10); n == 0 { fmt.Println(“That's too low”) } else if n > 5 { fmt.Println(“That's too big:”, n) } else { fmt.Println(“That's a good number:”, n) } fmt.Println(n)

Attempting to run this code produces a compilation error:

undefined: n

Note

Technically, you can put any simple statement before the comparison in an if statement. This includes things like a function call that doesn’t return a value or assigning a new value to an existing variable. But don’t do this. Only use this feature to define new variables that are scoped to the if/else statements; anything else would be confusing.

Also be aware that just like any other block, a variable declared as part of an if statement will shadow variables with the same name that are declared in containing blocks.

golang_if.txt · Last modified: 2025/02/01 06:54 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki