Recap - Shape Calculator
Part of the Object Oriented Programming section of Coddy's GO journey — lesson 33 of 107.
Challenge
EasyLet's build a shape calculator that brings together all the interface concepts from this chapter. You'll create a system where different geometric shapes can be processed uniformly through a shared interface, demonstrating the power of polymorphism in Go.
You'll organize your code across three files:
shape.go: Define aShapeinterface with two methods:Area() float64andPerimeter() float64. Also create a function calledDescribeShapethat accepts anyShapeand returns a formatted string showing both its area and perimeter.shapes.go: Create two structs that implement theShapeinterface:- A
RectanglewithWidthandHeightfields - A
Circlewith aRadiusfield
Area()andPerimeter()methods, plus aString()method (implementingfmt.Stringer) that returns a readable description of the shape.- A
main.go: Read shape data from input, create the appropriate shapes, and use yourDescribeShapefunction to display information about each one. Also print each shape directly to demonstrate theStringerinterface.
The following inputs will be provided:
- Line 1: Rectangle width (float)
- Line 2: Rectangle height (float)
- Line 3: Circle radius (float)
For calculations, use 3.14159 as the value of pi. Circle perimeter is 2 * pi * radius.
Your String() methods should return:
- Rectangle:
Rectangle(Width x Height) - Circle:
Circle(Radius: R)
Your DescribeShape function should return:
Area: [area], Perimeter: [perimeter]Format all float values with two decimal places using %.2f.
For example, given 4, 3, and 5, your output should be:
Rectangle(4.00 x 3.00)
Area: 12.00, Perimeter: 14.00
Circle(Radius: 5.00)
Area: 78.54, Perimeter: 31.42Print each shape first (using its String() method), then its description from DescribeShape. Process the rectangle first, then the circle.
Try it yourself
package main
import (
"fmt"
)
func main() {
// Read input values
var width, height, radius float64
fmt.Scanln(&width)
fmt.Scanln(&height)
fmt.Scanln(&radius)
// TODO: Create a Rectangle with the given width and height
// TODO: Create a Circle with the given radius
// TODO: Print the rectangle (uses String() method)
// TODO: Print the rectangle's description using DescribeShape()
// TODO: Print the circle (uses String() method)
// TODO: Print the circle's description using DescribeShape()
}
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