To easily initialize a local variable for an if conditional statement in Golang, you can write the variable initialization code after the keyword if
followed by the ;
symbol (semi-colon) and then the conditional statement.
TL;DR
package main
import "fmt"
func main() {
// a simple if conditional statement
// and a local variable called `greeting`
// with the value of `Hey`
if greeting := "Hey"; 3 < 5 {
fmt.Printf(greeting)
fmt.Printf(" Yes, it is true!")
}
// using the `greeting` variable outside the
// if conditional statement won't work
fmt.Printf(greeting); // ❌ undefined: greeting. Go build failed.
}
For example, let's say we have an if conditional statement that checks if the value 3
is less than the value 5
and if it's true (obviously) should print the text Yes, it is true!
to the terminal.
It will look like this,
package main
import "fmt"
func main() {
// a simple if conditional statement
if 3 < 5 {
fmt.Printf("Yes, it is true!")
}
}
Now to easily initialize a local variable for the if conditional block, we can specify the variable initialization after the if
keyword and end the variable initialization with the ;
symbol (semi-colon).
Let's make a local variable called greeting
with the value of Hey
and then print it to the terminal.
It can be done like this,
package main
import "fmt"
func main() {
// a simple if conditional statement
// and a local variable called `greeting`
// with the value of `Hey`
if greeting := "Hey"; 3 < 5 {
fmt.Printf(greeting)
fmt.Printf(" Yes, it is true!")
}
}
Now if you run the program, you can see an output like this,
Hey Yes, it is true!
Finally, to prove that this is only available in the if conditional block we specified. Let's also try to use the greeting
variable outside the if conditional statement.
It can be done like this,
package main
import "fmt"
func main() {
// a simple if conditional statement
// and a local variable called `greeting`
// with the value of `Hey`
if greeting := "Hey"; 3 < 5 {
fmt.Printf(greeting)
fmt.Printf(" Yes, it is true!")
}
// using the `greeting` variable outside the
// if conditional statement won't work
fmt.Printf(greeting); // ❌ undefined: greeting. Go build failed.
}
As soon as you run the program the Go compiler will show you an error saying undefined: greeting. Go build failed.
which proves the variable is declared locally to the if conditional statement.
We have successfully initialized a local variable for an if conditional statement in Golang/Go. Yay 🥳!
See the above code live in The Go Playground.
That's all 😃!
Top comments (0)