Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return pointer to local struct

Tags:

go

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?

like image 782
demi Avatar asked Dec 05 '12 02:12

demi


People also ask

Can we return pointer to structure?

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.

Can you return a pointer to a local variable?

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.

Can you return a local struct in C?

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.

How do you pass or return a structure to from a function in C?

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 .


2 Answers

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

like image 77
Lily Ballard Avatar answered Oct 07 '22 22:10

Lily Ballard


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.

like image 41
masebase Avatar answered Oct 07 '22 21:10

masebase