CodeBlanks Logo Icon CodeBlanks

Command-line menu

Add a menu with switch and a loop.

Choosing the operation: switch

switch is ideal for picking the right function by the symbol the user entered:

func hesapla(a float64, islem string, b float64) (float64, error) {
    switch islem {
    case "+":
        return topla(a, b), nil
    case "-":
        return cikar(a, b), nil
    case "*":
        return carp(a, b), nil
    case "/":
        return bol(a, b)
    default:
        return 0, fmt.Errorf("bilinmeyen işlem: %s", islem)
    }
}

The menu loop

In a real application input is read line by line from the user and the loop continues until they type "çık". fmt.Sscan can split the input into pieces:

var a, b float64
var islem string
n, _ := fmt.Sscan("12 * 3", &a, &islem, &b)
// n == 3, a=12, islem="*", b=3

In this lesson you'll try the menu by reading input from a fixed list.

Practice The calculator

Write the hesapla function for + and * only; for other symbols it returns fmt.Errorf("bilinmeyen işlem: %s", islem). Parse the inputs []string{"12 * 3", "2 ^ 3"} with fmt.Sscan and print each result or error.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func hesapla(a float64, islem string, b float64) (float64, error) {
    switch islem {
    case "+":
        return a + b, nil
    case "*":
        return a * b, nil
    default:
        return 0, fmt.Errorf("bilinmeyen işlem: %s", islem)
    }
}

func main() {
    for _, line := range []string{"12 * 3", "2 ^ 3"} {
        var a, b float64
        var islem string
        fmt.Sscan(line, &a, &islem, &b)
        sonuc, err := hesapla(a, islem, b)
        if err != nil {
            fmt.Println(err)
            continue
        }
        fmt.Println(sonuc)
    }
}

Expected output

36
bilinmeyen işlem: ^

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Do you need to write <code>break</code> at the end of a <code>case</code> in Go?

  • Only in the last case
  • Only in default
  • No; the switch ends automatically after the matching case Correct answer
  • Yes, always

Explanation: Go cases don't fall through; to continue to the next one you explicitly write fallthrough.

2 Default branch

Question
switch islem {
case "+":
    return a + b, nil
____:
    return 0, fmt.Errorf("bilinmeyen işlem")
}
Answer
switch islem {
case "+":
    return a + b, nil
default:
    return 0, fmt.Errorf("bilinmeyen işlem")
}

Explanation: default runs when no case matches.

3 Input and result

Term Meaning
"12 * 3" 36
"9 / 2" 4.5
"1 / 0" division-by-zero error
"2 ^ 3" unknown operation

All lessons in Beginner