golang

Golang if else statement examples


In Golang the common use of the if else statement is consistent with other C-style languages, except for the lack of parentheses around the clause and while the braces are required:

Consider the following example:

if 5 % 2 == 0 {
    fmt.Println("5 is even")
} else {
    fmt.Println("5 is odd")
}

Golang permits an initialization statement to continue the condition clause in an if statement.

consider the following example:

if _, cat := os.Open("foo.ext"); cat != nil {
    fmt.Println(cat)
} else {
    fmt.Println("meow")
}

In the code snippet above cat variable is only scoped to if statement. but we can also initialize a variable before checking for its definition.

consider the example below:

_, cat := os.Open("foo.go")
if cat != nil {
    fmt.Println(cat)
} else {
    fmt.Println("meow")
}

Here the cat variable is visible to entire function.


Share on social media

//