0PricingLogin
Go Academy · Lesson

Constructor Patterns

Building idiomatic Go constructors

Why Constructors?

Go has no new keyword for types and no class constructors. The convention is a function named New... that validates inputs and returns an initialized value or pointer.

Simple New Function

Return a pointer to ensure the caller works with a shared instance:

package main
import "fmt"

type Server struct {
    Host string
    Port int
}

func NewServer(host string, port int) *Server {
    return &Server{Host: host, Port: port}
}

func main() {
    s := NewServer("localhost", 8080)
    fmt.Println(s.Host, s.Port)
}

All lessons in this course

  1. Defining and Using Structs
  2. Methods on Structs
  3. Constructor Patterns
  4. Anonymous Structs and Composition
← Back to Go Academy