Recap - Simple Calculator
Part of the Object Oriented Programming section of Coddy's GO journey — lesson 11 of 107.
Challenge
HardBuild a complete Calculator using everything you've learned:
- Struct (Exported Fields) — Define
CalculatorwithName(string),LastResult(float64), andHistory(int) - Constructor Function —
NewCalculator(name string)returns*Calculator. If name is empty, default to"Unnamed" - Value Receiver —
GetInfo()returns the calculator's name as a formatted string - Pointer Receivers —
Add,Subtract,Multiplyeach store the result inLastResultand incrementHistory - Divide — pointer receiver returning
(float64, string). If dividing by zero, return0and"Error: division by zero"without updatingHistoryorLastResult
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
1Fundamentals of Go OOP
External FilesGo Workspace & ModulesPackages & ImportsExported vs Unexported NamesIntroduction to OOP in GoStructs as ClassesDefining Methods on StructsPointer vs Value ReceiversStruct InitializationConstructor FunctionsRecap - Simple Calculator4Interfaces
Introduction to InterfacesImplicit ImplementationInterface as ContractEmpty Interface (any)Type AssertionType SwitchInterface CompositionStringer & Error InterfacesRecap - Shape Calculator7Encapsulation
Exported vs Unexported FieldsPackage-Level EncapsulationGetter & Setter MethodsInformation Hiding in GoRecap - Student Records10Generics (Go 1.18+)
Introduction to GenericsType ParametersType ConstraintsGeneric StructsGeneric Methods WorkaroundRecap - Generic Collection2Types & Structs Deep Dive
Basic & Composite TypesCustom Type DefinitionsStruct TagsAnonymous StructsNested StructsZero Values & DefaultsRecap - Contact Book5Composition Over Inheritance
Why Go Has No InheritanceStruct Embedding BasicsMethod PromotionEmbedding Multiple StructsEmbedding vs AggregationShadowing Embedded MethodsRecap - Employee Hierarchy8Error Handling & OOP
The error InterfaceCustom Error TypesError Wrapping (fmt.Errorf)Sentinel Errorserrors.Is() and errors.As()Panic, Defer, and RecoverRecap - File Parser3Pointers & Memory
Pointer Basics in GoPointers to StructsPass by Value vs ReferenceThe new() FunctionGarbage Collection in GoRecap - Linked List Builder6Polymorphism in Go
Polymorphism via InterfacesDuck Typing in GoInterface Satisfaction RulesPolymorphic CollectionsDependency InjectionRecap - Payment Processor9Concurrency & OOP
Goroutines BasicsChannels & CommunicationBuffered vs Unbuffered ChanSelect Statementsync.Mutex & sync.RWMutexsync.WaitGroupThread-Safe Struct DesignRecap - Worker Pool