Can pointers own data in go?

Hi there! Very new to go and have a question about pointers.

Was following a tutorial here: Writing Web Applications - The Go Programming Language.

This function sort of has me confused :frowning:

func loadPage(title string) (*Page, error) {
    filename := title + ".txt"
    body, err := os.ReadFile(filename)
    if err != nil {
        return nil, err
    }
    return &Page{Title: title, Body: body}, nil
}

not relevant to my question but here is the page struct for completeness

type Page struct {
    Title string
    Body  []byte
}

Coming from C++ and Rust, this code seems to have an obvious flaw. It returns a pointer to data created within the functions scope.

In cpp or rust this would lead to dangling pointer or just wouldn’t compile.
Does this pointer “own” the data it points to? When the pointer goes out of scope later is the data cleared up?

This leads to even more questions. What if I have a struct as a variable AND have a pointer to said struct? Which one “owns” that data from a garbage collection standpoint?
This playground code makes me think they both “own” it (sort of like reference counting)

Any and all insight is really appreciated :slight_smile:

PS: to be clear I’m more interested discovering a go-footgun or nooby mistake than I a am in the inner workings of the go language (information on both is welcome tho :+1:.

In this case your pointer is allocated in the heap (use for new and make creation process) and GC (Garbage Collector) collects memory in the heap when it is unused (referenced)
There is an interesting article about this in GoLang Memory Management - Calsoft Blog

Even if it isn’t a dangling pointer I don’t understand why you would return a pointer some data when you could just return the data itself.

Does it prevent a copy? Could the user not just create a pointer to the data they are returned (assuming they want/need to)

Playing with the code in my editor it seems like returning a pointer here makes it so that there is a sensible default for the page: nil. If page == nil that implies that err != nil.

Is this a valid reason to use a pointer over the type it points to?

Is there really a big difference in having a type or a pointer to it in go? I was thinking that certain functions would want Page vs *Page but we can just ref or deref the variable?

I think they are using a pointer here because the Page struct would be large, maybe for the Body field…

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.