if/else
Branching with if
and else
is same as in other languages. The if
statement is used to execute a block of code if a condition is true. The else
statement can be used to execute a block of code if the condition is false. There is also else if
for multiple conditions.
a := 10
if a > 5 {
fmt.Println("a is greater than 5")
} else if a < 5 {
fmt.Println("a is less than 5")
} else {
fmt.Println("a is equal to 5")
}
You can also use if
in a inline value assignment. This is useful when you want to declare a variable and check its value in the same line.
if a := 10; a > 5 {
fmt.Println("a is greater than 5")
} else {
fmt.Println("a is less than or equal to 5")
}
In more complex cases, this is useful to getting the value of some function without having to declare a variable outside the scope of the if
statement.
if ok := someFunction(); !ok {
fmt.Println("It's not ok")
}
Loop or iteration is done with for
statement. The for
statement can be used to iterate over a range of values, such as an array or a slice. It can also be used to create an infinite loop.
Assuming that you've declared an array or slice, you can use either looping as above or using range. The difference is if you opt for using range
, you can get the index and value of the element in the array or slice. While using for
as above, you can only get the index.
It is common in other languages to use while
loop. But there is no while
loop in Go. You can use for
statement to create a while
loop.
i := 0
for i < 5 {
fmt.Println(i)
i++
}
Just beware if you use for
statement without any condition, it will create an infinite loop.
for {
fmt.Println("This is an infinite loop that never ends 🧞")
}
switch
Switch statements in Go are similar to other languages. The switch
statement allows you to execute different blocks of code based on the value of a variable.
package main
import "fmt"
func main() {
day := 3
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
default:
fmt.Println("Unknown day")
}
}
defer
The defer
statement is rather unique to Go. It is used to schedule a function call to be executed after the function completes. The defer
statement is executed in LIFO (Last In First Out) order, which means that the last deferred function will be executed. This is useful for cleaning up resources, such as closing files or network connections. I swear that you will use this a lot in your code 🤞.
The pyramid problem is a common learning exercise in programming, especially when it comes to flow control. The goal is to print a pyramid of numbers. The pyramid has a certain number of rows, and each row contains a certain number of numbers. Asterisks are printed in a pyramid shape, with the first row containing one number, the second row containing two numbers, and so on.
*
***
*****
*******
*********