Why use &struct over struct

func main() {
    p1 := &Page{Title: "TestPage", Body: []byte("This is a sample Page.")}
    p1.save()
    p2, _ := loadPage("TestPage")
    fmt.Println(string(p2.Body))
}

This code is part of the Writing Web Applications section of golang tutorial. My question is, why we’re using &Page over just Page in the above snippet.

1 Like

There’s no reason. In this scenario, it would work the same without the &.

Usually, pointers are useful than the objects themselves. You can perform nil checks and set object properties through function receivers instead of changing property directly.

However, objects without object pointers are also passed by reference which means you can also change their properties directly but not through function receivers, you can not also do nil checks.

It is a general thumb of the rule to create NewApple() *apple { return &apple{} } so when you have an interface, you can easily modify it to NewApple() Fruit {return &apple{} } keep in mind that this is not necessary for your small codebases.

1 Like