Building a Simple CLI App
Build a simple command-line calculator application.
Learning objective: Combine variables, input, switch, and conditions in a small CLI program.
What Is a CLI App?
A command-line interface app accepts input from the terminal and displays results as text.
Getting User Input
The fmt.Scanln function can read simple input from the user.
Calculator Logic
You can combine variables, input, and switch statements to build a small calculator.
Example Code
Create or update your Go file, then run the program using go run main.go.
package main
import "fmt"
func main() {
var a, b float64
var op string
fmt.Print("Enter first number: ")
fmt.Scanln(&a)
fmt.Print("Enter operator (+ - * /): ")
fmt.Scanln(&op)
fmt.Print("Enter second number: ")
fmt.Scanln(&b)
switch op {
case "+":
fmt.Println("Result:", a+b)
case "-":
fmt.Println("Result:", a-b)
case "*":
fmt.Println("Result:", a*b)
case "/":
if b == 0 {
fmt.Println("Cannot divide by zero")
} else {
fmt.Println("Result:", a/b)
}
default:
fmt.Println("Unknown operator")
}
}
Key points to remember
- CLI apps are useful for beginner projects.
- Use clear prompts so users know what to enter.
- Always check for invalid operations such as division by zero.
Practice Exercises
- Create a calculator with addition only.
- Add subtraction and multiplication.
- Add division with zero checking.
Continue Learning
After this lesson, continue to the next lesson or explore related tutorials on VisualStudioTutor.com.