Menu
Coddy logo textTech

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 icon

Challenge

Medium

Create a constructor function NewBankAccount for the BankAccount struct with validation:

  • Takes name (string) and balance (float64) as parameters
  • If name is empty, default to "Unnamed"
  • If balance is negative, default to 0
  • Set Owner to "Default Owner" always
  • Return a pointer to the new struct

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)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online Go compiler