Go
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.
Exercise 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.
Show example solution
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)
}
}
Test yourself
-
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
- Yes, always
Show answer
No; the switch ends automatically after the matching case — Go cases don't fall through; to continue to the next one you explicitly write fallthrough.
-
Default branch
switch islem {
case "+":
return a + b, nil
____:
return 0, fmt.Errorf("bilinmeyen işlem")
}
Show answer
switch islem {
case "+":
return a + b, nil
default:
return 0, fmt.Errorf("bilinmeyen işlem")
}
-
Input and result
- "12 * 3"
- 36
- "9 / 2"
- 4.5
- "1 / 0"
- division-by-zero error
- "2 ^ 3"
- unknown operation
Next lesson: func declaration