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
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
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 .