Command-Line Calculator
Start with Command-Line Calculator
Learn command-line calculator through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of command-line calculator.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Build a command-line calculator by separating argument parsing, operation selection and evaluation. A useful calculator reports invalid operations and division by zero rather than panicking.
The starter version uses fixed arguments so it runs in any online compiler; replace them with os.Args[1:] for a real CLI.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
CLI extension: change args := []string{...} to args := os.Args[1:] after importing os. Require exactly three arguments. Try go run . 12 / 4 and test malformed input.
Tests: write table-driven tests for each operator, invalid operators, invalid numbers and division by zero.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"strconv"
)
func calculate(a float64, op string, b float64) (float64, error) {
switch op {
case "+":
return a + b, nil
case "-":
return a - b, nil
case "*":
return a * b, nil
case "/":
if b == 0 {
return 0, fmt.Errorf("divide by zero")
}
return a / b, nil
default:
return 0, fmt.Errorf("unsupported operator %q", op)
}
}
func main() {
args := []string{"12", "*", "3"}
a, e1 := strconv.ParseFloat(args[0], 64)
b, e2 := strconv.ParseFloat(args[2], 64)
if e1 != nil || e2 != nil {
fmt.Println("Invalid number")
return
}
result, err := calculate(a, args[1], b)
fmt.Println("Result:", result, "Error:", err)
}
Output
Result: 36 Error: <nil>Trace what the program does
The two numeric strings parse as 12 and 3. The multiplication branch computes 36 and returns no error.
Avoid common mistakes
- Check the argument count before indexing os.Args in a real CLI.
- Do not use integer division if users expect fractional results.
Try it yourself
Accept three command-line arguments and display usage guidance when the invocation is malformed.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Command-Line Calculator in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.