Introduction to OOP in Go
Part of the Object Oriented Programming section of Coddy's GO journey — lesson 5 of 107.
Go doesn't have classes, but it achieves object-oriented programming through structs and methods. A struct groups related data, and methods define behavior attached to that struct.
Define a struct to hold data
type Dog struct {
Name string
Age int
}Attach a method to the struct
func (d Dog) Bark() string {
return d.Name + " says Woof!"
}Create an instance and use it
package main
import "fmt"
type Dog struct {
Name string
Age int
}
func (d Dog) Bark() string {
return d.Name + " says Woof!"
}
func main() {
myDog := Dog{Name: "Buddy", Age: 3}
fmt.Println(myDog.Bark()) // Output: Buddy says Woof!
fmt.Println(myDog.Age) // Output: 3
}In Go, the (d Dog) part before the method name is called a receiver. It connects the method to the Dog struct, similar to how methods belong to classes in other languages.
Challenge
EasyCreate a Cat struct with a method to practice Go's approach to OOP:
- Define a
Catstruct withName(string) andAge(int) fields - Add a
Speakmethod that returns the cat's name followed by" says Meow!"
Cheat sheet
Go achieves object-oriented programming through structs and methods. A struct groups related data, and methods define behavior attached to that struct.
Define a struct to hold data:
type Dog struct {
Name string
Age int
}Attach a method to the struct using a receiver:
func (d Dog) Bark() string {
return d.Name + " says Woof!"
}The (d Dog) part before the method name is the receiver, which connects the method to the struct.
Create an instance and use it:
myDog := Dog{Name: "Buddy", Age: 3}
fmt.Println(myDog.Bark()) // Output: Buddy says Woof!
fmt.Println(myDog.Age) // Output: 3Try it yourself
package main
import "fmt"
func main() {
var name string
var age int
fmt.Scan(&name, &age)
cat := Cat{Name: name, Age: age}
fmt.Printf("Name: %s\n", cat.Name)
fmt.Printf("Age: %d\n", cat.Age)
fmt.Println(cat.Speak())
}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