How can I improve this beginner Go CLI calculator and handle input validation correctly?

2 weeks ago 20
ARTICLE AD BOX

I am a beginner learning Go and building a simple CLI calculator as practice.

Goal:
I want to read two numbers and an operator from the user, perform the calculation, and handle invalid input in a beginner-friendly way.

Problem / Confusion:
I am confused about how to properly validate user input using fmt.Scanln.
Sometimes invalid input causes unexpected behavior, and I’m not sure if my loop and error handling are correct or idiomatic Go.

I would like to know:

How to improve this code structure in a beginner-friendly way

Whether my input validation approach is correct

What I should change to make this more idiomatic Go

Code:

// A beginner calculator project package main import "fmt" func main() { defer fmt.Println("GoodBye!") fmt.Println("WELCOME TO MY CLI CALCULATOR") for { var firstNum, secondNum int // using int because modulus can't work with floats var operators string fmt.Print("Enter First Number: ") _, err := fmt.Scanln(&firstNum) if err != nil { fmt.Println("Error: Enter a valid number") continue } fmt.Print("Enter Operator (+, -, /, *): ") fmt.Scanln(&operators) fmt.Print("Enter Second Number: ") _, err = fmt.Scanln(&secondNum) if err != nil { fmt.Println("Error: Enter a valid number") continue } var result int switch operators { case "+": result = firstNum + secondNum case "-": result = firstNum - secondNum case "*": result = firstNum * secondNum case "/": if secondNum == 0 { fmt.Println("Error: Division by zero") continue } result = firstNum / secondNum default: fmt.Println("Invalid operator") continue } fmt.Println(firstNum, operators, secondNum, "=", result) fmt.Print("Do you want to continue (y/n): ") var choice string fmt.Scanln(&choice) if choice == "n" { break } } fmt.Println("Program Ended") }

Question:
What is the correct and beginner-friendly way to improve this code, especially input validation and control flow?

Read Entire Article