C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The condition of an if-statement has no surrounding parentheses. The body statements are surrounded by curly braces.
Note 2: In Go the starting curly brace must be placed at the end of the same line. The Gofmt command can help with formatting issues.
Golang program that uses if, else statements
package main
import "fmt"
func main() {
value := 10
// Test the value with an if-else construct.
if value >= 5 {
fmt.Println(5)
} else if value >= 15 {
fmt.Println(15) // Not reached.
} else {
fmt.Println("?") // Not reached.
}
}
Output
5
Scope: The variable is scoped to the if-statement and its contents. Here we cannot reference "t" outside the if.
Golang program that uses if with initialization statement
package main
import "fmt"
func test() int {
return 100
}
func main() {
// Initialize a variable in an if-statement.
// ... Then check it against a constant.
if t := test(); t == 100 {
fmt.Println(t)
}
}
Output
100
Undefined: If we use the variable outside its scope, an "undefined" error will occur. This is a compile-time error.
Golang program that uses causes error, undefined variable
package main
import "fmt"
func main() {
mult := 10
// The variable "t" can be accessed only in the if-statement.
if t := 100 * mult; t >= 200 {
fmt.Println(t)
}
// This causes an error.
fmt.Println(t)
}
Output
C:\programs\file.go:16: undefined: t
Golang program that has unexpected newline error
package main
import "fmt"
func main() {
// This program won't compile.
value := 10
if value == 20 {
fmt.Println(20)
}
else {
fmt.Println(0)
}
}
Output
# command-line-arguments
syntax error: unexpected semicolon or newline before else
syntax error: unexpected {