Defining Methods on Structs
Part of the Object Oriented Programming section of Coddy's GO journey — lesson 7 of 107.
Methods in Go are functions with a special receiver argument that associates the function with a struct type.
Method syntax
func (receiverName StructType) MethodName() ReturnType {
// method body
}Define a struct with methods
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}Methods with parameters
func (r Rectangle) Scale(factor float64) float64 {
return r.Area() * factor
}Calling methods
rect := Rectangle{Width: 5, Height: 3}
fmt.Println(rect.Area()) // Output: 15
fmt.Println(rect.Perimeter()) // Output: 16
fmt.Println(rect.Scale(2)) // Output: 30The receiver (r Rectangle) lets you access the struct's fields inside the method using the receiver variable r. Methods can call other methods on the same struct.
Challenge
MediumAdd three methods to the Circle struct:
Area— returnsmath.Pi * radius * radiusCircumference— returns2 * math.Pi * radiusDescribe— returns a string:"Circle with radius X.XX"
Cheat sheet
Methods in Go are functions with a special receiver argument that associates the function with a struct type.
Method syntax:
func (receiverName StructType) MethodName() ReturnType {
// method body
}Example with a struct and methods:
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}Methods can accept parameters:
func (r Rectangle) Scale(factor float64) float64 {
return r.Area() * factor
}Calling methods:
rect := Rectangle{Width: 5, Height: 3}
fmt.Println(rect.Area()) // Output: 15
fmt.Println(rect.Perimeter()) // Output: 16
fmt.Println(rect.Scale(2)) // Output: 30The receiver allows you to access the struct's fields inside the method. Methods can call other methods on the same struct.
Try it yourself
package main
import "fmt"
func main() {
var radius float64
fmt.Scan(&radius)
c := Circle{Radius: radius}
fmt.Printf("Area: %.2f\n", c.Area())
fmt.Printf("Circumference: %.2f\n", c.Circumference())
fmt.Printf("Description: %s\n", c.Describe())
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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