This is a feature in Go that allows you to declare and initialize variables within an if
, for
, or switch
statement
It's a concise way to create variables that have a limited scope, typically used within the block associated with the conditional statement
Here's the basic syntax for a short variable declaration in a conditional statement
if varName := expression; condition {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Here's how it works:
varName
is the name of the variable you want to declare and initialize.expression
is an expression that provides the initial value for the variable.condition
is a boolean condition that determines whether the code inside the if
block or the else
block will be executed.The variable varName
is only accessible within the scope of the if
block, which is delimited by curly braces {}
. If the condition is true, the code within the if
block is executed, and if the condition is false, the code within the else
block is executed.
Here's an example:
if num := 10; num > 5 {
fmt.Println("Number is greater than 5")
} else {
fmt.Println("Number is not greater than 5")
}