Control Structures

If/else

Self explaining:

if choice == 1 {
	fmt.Printf("Your balance is: %.2f GO", accountBalance)
} else if choice == 2 {
	var depositAmount float64
	fmt.Print("How much GO do you want to deposit: ")
	fmt.Scan(&depositAmount)
	accountBalance += depositAmount
	fmt.Printf("New account balance: %.2f GO", accountBalance)
}

In Go, we can break out of if statements by making a naked return:

if depositAmount <= 0 {
	fmt.Println("Deposit amount must be greater than 0.")
	return
}

This stops the execution of the function it uses. If you return inside the main function, the program will stop executing.

We can also directly initialize a variable inside the if scope. It will only be used inside the if block in this case and has no longer a context after the if block. This is easier then initializing a variable before and using it, instead we can just use it and get rid of it:

func main() {
    fmt.Println("Hello World")
    name := "Halula"
    
    if lenName := len(name); lenName == 6 {
        fmt.Println("Longer than 6")
    } 
}

For loops

Self explaining:

for i := 0; i < 5; i++ {
    // logic
}

If we only use the for keyword without any initial variable, condition and increment, the loop will run forever till it gets out of the loop with the break keyword:

for {
    // logic
}

The break keyword breaks out of the loop. It makes sure the loop is ended and the next code outside the loop is executed.

The continue keyword, restarts the loop. For example if we check if the input is greater than 0, but the user enters 0, instead of return or breaking it, we use continue, the user gets another try or starts as said again in the beginning of the loop e.g. menu of the program.

Switch Statements

Self explaining:

choice := 2

switch choice {
case 1:
	// code
case 2:
	// code
default:
	// code | if everything else then 1 or 2
	return // breaks out of the switch and terminates the program!
	// if it should not end, use if-else instead.
}

Last updated