I see some code samples with constructs like this:
type point struct { x, y int } func newPoint() *point { return &point{10, 20} }
I have C++ background and it seems like error for me. What are the semantic of such construct? Is new point allocated on the stack or heap?
Use Pointer Notation to Return struct From Function The pointer serves as a handle to the object and its size is fixed regardless of the structure stored there. Using pointers to return struct potentially reduces memory traffic and gives code more performance.
The return statement should not return a pointer that has the address of a local variable ( sum ) because, as soon as the function exits, all local variables are destroyed and your pointer will be pointing to someplace in the memory that you no longer own.
You can return a structure from a function (or use the = operator) without any problems. It's a well-defined part of the language. The only problem with struct b = a is that you didn't provide a complete type.
Return struct from a function Here, the getInformation() function is called using s = getInformation(); statement. The function returns a structure of type struct student . The returned structure is displayed from the main() function. Notice that, the return type of getInformation() is also struct student .
Go performs pointer escape analysis. If the pointer escapes the local stack, which it does in this case, the object is allocated on the heap. If it doesn't escape the local function, the compiler is free to allocate it on the stack (although it makes no guarantees; it depends on whether the pointer escape analysis can prove that the pointer stays local to this function).
The Golang "Documentation states that it's perfectly legal to return a pointer to local variable." As I read here
https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/EYUuead0LsY
I looks like the compiler sees you return the address and just makes it on the heap for you. This is a common idiom in Go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With