This content originally appeared on CodeSource.io and was authored by Deven
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.
The post Golang if else statement examples appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Deven
Deven | Sciencx (2021-02-08T15:27:48+00:00) Golang if else statement examples. Retrieved from https://www.scien.cx/2021/02/08/golang-if-else-statement-examples/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.