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 post Golang if else statement examples appeared first on CodeSource.io.


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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Golang if else statement examples." Deven | Sciencx - Monday February 8, 2021, https://www.scien.cx/2021/02/08/golang-if-else-statement-examples/
HARVARD
Deven | Sciencx Monday February 8, 2021 » Golang if else statement examples., viewed ,<https://www.scien.cx/2021/02/08/golang-if-else-statement-examples/>
VANCOUVER
Deven | Sciencx - » Golang if else statement examples. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/02/08/golang-if-else-statement-examples/
CHICAGO
" » Golang if else statement examples." Deven | Sciencx - Accessed . https://www.scien.cx/2021/02/08/golang-if-else-statement-examples/
IEEE
" » Golang if else statement examples." Deven | Sciencx [Online]. Available: https://www.scien.cx/2021/02/08/golang-if-else-statement-examples/. [Accessed: ]
rf:citation
» Golang if else statement examples | Deven | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.