A small, idiomatic Go calculator designed for teaching and quick demos. The project includes a focused calc package with pure functions, unit tests, and a tiny CLI that supports flags, positional arguments, and an interactive REPL.
Files
calc/: calculator package implementing arithmetic and factorial.cmd/calc: command-line program and interactive REPL.
Supported operations
- add, sub, mul, div, pow, fact
Requirements
- Go 1.20+ installed and available on your PATH.
Quick start
- From the project root, run tests:
cd /home/arian/project/golang
go test ./...- Run the CLI (non-interactive examples):
# flags
go run ./cmd/calc -op add -a 2 -b 3
go run ./cmd/calc -op div -a 10 -b 2
# positional
go run ./cmd/calc add 2 3- Start the interactive REPL (recommended for demos):
go run ./cmd/calc
# Example interactive session (you can type these lines when prompted):
# calc> + 2 3 => prints 5
# calc> pow 2 10 => prints 1024
# calc> fact 5 => prints 120
# calc> quit => exitREPL features
- Prompt:
calc> - Accepts single-line commands:
add 2 3,+ 2 3,pow 2 10,fact 5. - If you enter only an operation (e.g.
+), the REPL will prompt for the operands. - Commands:
help,quit,exit,q.
How it works (brief)
calcpackage (calc/calc.go): small pure functions returning values or errors where appropriate.Add/Sub/Mul/Powreturnfloat64results.Div(a,b) (float64, error)returns an error for division by zero.Factorial(n uint64) (uint64, error)returns an error whenn > 20to avoiduint64overflow.
cmd/calc/main.go: CLI and REPL. It supports three modes:- Flag mode:
-op,-a,-b,-nfor scripting. - Positional mode:
go run ./cmd/calc add 2 3. - REPL mode:
go run ./cmd/calcfor interactive use.
- Flag mode:
Design notes (for a short presentation)
- Small package surface makes code easy to read and test.
- Explicit error returns (Go idiom) — no panics for normal input errors.
- Tests live next to the package in
calc/calc_test.goand cover happy-path and error cases.
Presentation tips
- Show
Divand explain explicit error handling for divide-by-zero. - Show
Factorialand explain the overflow guard (n <= 20) and whybig.Intwould be used for larger factorials. - Run
go test ./...live to demonstrate automated correctness.
Extending the project
- Add
big.Intfactorial if you need arbitrarily large results. - Add an expression parser or REPL history for a richer demo.
If you want, I can also add a short scripts/demo.sh that runs a few example commands and prints outputs for slide screenshots.