Design constructors and validation
Design constructors and validation
Go has no special constructor syntax. A function named NewType is a convention that can initialize a struct, apply defaults and reject invalid input. When failure is possible, returning (T, error) or (*T, error) makes failure explicit. A non-nil error signals that the caller should not use the result as successful.
package main
import ( "errors" "fmt")
type Product struct { Name string Quantity int}
func NewProduct(name string, quantity int) (Product, error) { if name == "" || quantity < 0 { return Product{}, errors.New("invalid product") } return Product{Name: name, Quantity: quantity}, nil}func main() { p, err := NewProduct("Pen", 3) if err != nil { fmt.Println(err) return } fmt.Println(p.Name, p.Quantity) _, err = NewProduct("", -1) fmt.Println(err)}The function checks the invariant before constructing a result. errors.New creates an error with the given message; nil means success. The caller checks err before accessing the successful record. Because fields are exported, callers can still construct invalid values or mutate fields directly. A constructor alone does not enforce invariants everywhere.
Expected output:
Pen 3invalid productKeep the zero value meaningful
package main
import ( "errors" "fmt")
type Counter struct{ n int }
func NewCounter(start int) (Counter, error) { if start < 0 { return Counter{}, errors.New("negative start") } return Counter{n: start}, nil}func main() { var zero Counter fmt.Println(zero.n) c, err := NewCounter(5) if err != nil { fmt.Println(err) return } fmt.Println(c.n) _, err = NewCounter(-1) fmt.Println(err)}A lowercase field restricts direct access from other packages, not from code in the same package. Other packages can still create the zero value. Design the zero value deliberately, or document operations that require initialization. Methods and package boundaries will provide more tools for maintaining invariants later.
Expected output:
05negative startTry it locally
Define Ticket with Seats int. Write NewTicket(seats int)(Ticket,error) accepting only 1 through 5 seats. Print Seats for 2 and the error for 0.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Structs and defined types 08: Design constructors and validation
Check the lesson objective before moving on.
Is NewProduct special syntax recognized by Go?
What should callers do before using a result from a fallible constructor?