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
- Defining and Using Structs
- Methods on Structs
- Constructor Patterns
- Anonymous Structs and Composition