Creating valid values in one place
Some types have rules for their starting values. Say every new bank account must start as open, and its first deposit can never be negative. If every part of the program builds accounts with its own struct literal, sooner or later one of them forgets a rule.
Some languages have a special constructor for this: code that runs every time a new value is made. Go has no constructor keyword. Instead, you write a normal function that builds the value and returns it. By convention, its name is New followed by the type name.
package main
import "fmt"
type Account struct {
Owner string
Balance int
Open bool
}
func NewAccount(owner string, deposit int) Account {
if deposit < 0 {
deposit = 0
}
return Account{
Owner: owner,
Balance: deposit,
Open: true,
}
}
func main() {
a := NewAccount("Alice", 100)
b := NewAccount("Bob", -20)
fmt.Printf("%+v\n", a)
fmt.Printf("%+v\n", b)
}
Output:
{Owner:Alice Balance:100 Open:true}
{Owner:Bob Balance:0 Open:true}
The rules now live in one place. Every account made with NewAccount is open, and Bob's negative deposit became 0. The callers only pass what changes from one account to the next: the owner and the deposit.
NewAccount is not special syntax. It is an ordinary function, and Go does not stop anyone from writing Account{} directly. The name tells other programmers that this is the right way to make an account.
Returning a pointer
A constructor often returns a pointer instead of a value. Putting & in front of a struct literal makes the struct and gives you its address:
package main
import "fmt"
type Account struct {
Owner string
Balance int
Open bool
}
func NewAccount(owner string, deposit int) *Account {
if deposit < 0 {
deposit = 0
}
return &Account{
Owner: owner,
Balance: deposit,
Open: true,
}
}
func (a *Account) Deposit(amount int) {
a.Balance += amount
}
func main() {
acc := NewAccount("Alice", 100)
acc.Deposit(50)
fmt.Println(acc.Balance)
fmt.Printf("%+v\n", acc)
}
Output:
150
&{Owner:Alice Balance:150 Open:true}
The return type is now *Account, a pointer to an account. The & at the start of the printed line tells you that acc is a pointer to the struct, not the struct itself.
You use the pointer just like the struct: acc.Balance and acc.Deposit(50) follow it for you, as you saw in the Pointers lesson. Because acc already is a pointer, the pointer receiver of Deposit changes the one account that NewAccount made.
Return a pointer when the value will be changed by pointer-receiver methods, or when different parts of the program should share one value. Return a plain value for small types that nobody changes after they are made.
In the exercise, finish NewOrder so it returns a pointer to a new order that follows the rules.