Menu
Coddy logo textTech

Recap - Simple Calculator

Part of the Object Oriented Programming section of Coddy's GO journey — lesson 11 of 107.

challenge icon

Challenge

Hard

Build a complete Calculator using everything you've learned:

  • Struct (Exported Fields) — Define Calculator with Name (string), LastResult (float64), and History (int)
  • Constructor FunctionNewCalculator(name string) returns *Calculator. If name is empty, default to "Unnamed"
  • Value ReceiverGetInfo() returns the calculator's name as a formatted string
  • Pointer ReceiversAdd, Subtract, Multiply each store the result in LastResult and increment History
  • Divide — pointer receiver returning (float64, string). If dividing by zero, return 0 and "Error: division by zero" without updating History or LastResult

Try it yourself

package main

import "fmt"

func main() {
    var name string
    var a, b float64
    fmt.Scan(&name, &a, &b)

    calc := NewCalculator(name)

    fmt.Println(calc.GetInfo())
    fmt.Printf("History: %d\n", calc.History)

    fmt.Printf("%.0f + %.0f = %.2f\n", a, b, calc.Add(a, b))
    fmt.Printf("%.0f - %.0f = %.2f\n", a, b, calc.Subtract(a, b))
    fmt.Printf("%.0f * %.0f = %.2f\n", a, b, calc.Multiply(a, b))

    result, err := calc.Divide(a, b)
    if err != "" {
        fmt.Println(err)
    } else {
        fmt.Printf("%.0f / %.0f = %.2f\n", a, b, result)
    }

    fmt.Printf("History: %d\n", calc.History)
    fmt.Printf("Last Result: %.2f\n", calc.LastResult)
}

All lessons in Object Oriented Programming