Constructor Functions
Part of the Object Oriented Programming section of Coddy's GO journey — lesson 10 of 107.
Go doesn't have constructors like other languages. Instead, the convention is to create a function named NewTypeName that returns an initialized struct, often as a pointer.
Basic constructor function
type Person struct {
Name string
Age int
}
func NewPerson(name string, age int) *Person {
return &Person{
Name: name,
Age: age,
}
}Constructor with default values
type Config struct {
Host string
Port int
Timeout int
}
func NewConfig(host string) *Config {
return &Config{
Host: host,
Port: 8080, // Default value
Timeout: 30, // Default value
}
}Constructor with validation
func NewPerson(name string, age int) *Person {
if name == "" {
name = "Unknown"
}
if age < 0 {
age = 0
}
return &Person{
Name: name,
Age: age,
}
}Using constructor functions
func main() {
p1 := NewPerson("Alice", 25)
fmt.Println(p1.Name) // Alice
p2 := NewPerson("", -5)
fmt.Println(p2.Name) // Unknown
fmt.Println(p2.Age) // 0
}Constructor functions return a pointer (*StructName) using &. This avoids copying the struct and lets methods with pointer receivers work directly. Validation and default values go inside the constructor.
Challenge
MediumCreate a constructor function NewBankAccount for the BankAccount struct with validation:
- Takes
name(string) andbalance(float64) as parameters - If
nameis empty, default to"Unnamed" - If
balanceis negative, default to0 - Set
Ownerto"Default Owner"always - Return a pointer to the new struct
Cheat sheet
Go uses constructor functions instead of constructors. The convention is to name them NewTypeName and return a pointer to the initialized struct.
Basic constructor function:
type Person struct {
Name string
Age int
}
func NewPerson(name string, age int) *Person {
return &Person{
Name: name,
Age: age,
}
}Constructor with default values:
func NewConfig(host string) *Config {
return &Config{
Host: host,
Port: 8080, // Default value
Timeout: 30, // Default value
}
}Constructor with validation:
func NewPerson(name string, age int) *Person {
if name == "" {
name = "Unknown"
}
if age < 0 {
age = 0
}
return &Person{
Name: name,
Age: age,
}
}Constructor functions return a pointer (*StructName) using & to avoid copying the struct and allow pointer receiver methods to work directly.
Try it yourself
package main
import "fmt"
func main() {
var name string
var balance float64
fmt.Scan(&name, &balance)
account := NewBankAccount(name, balance)
fmt.Printf("Account: %s\n", account.Name)
fmt.Printf("Balance: %.2f\n", account.Balance)
fmt.Printf("Owner: %s\n", account.Owner)
}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