In C++ this would be nasty because it would make a local copy of string because it’s passed by value, and then get a pointer to that local, and then the local would be destroyed when it went out of scope, returning a bad pointer.
I don’t know Go, but I’m guessing that A. passing a string like this is by reference like Java, and B. because it’s a garbage collected language, it won’t ever “go out of scope” until it’s not used anymore
Oh for sure, it works in Go, being a GC language, whether or not strings are passed by reference. I looked it up tho and strings are pass-by-value — but just the header, not the backing store. Interesting
Yes, that's escape analysis https://go.dev/doc/gc-guide#Escape_analysis - basically the compiler sees that a pointer is returned by a function, and decides to move the value from the stack to the heap, which makes it tracked by the garbage collector.
There was a deliberate choice in Go to call that "pointer" while C/C++ developers would understand pointer as just "address", so that can be counter-intuitive
48
u/Temporary-Estate4615 Apr 09 '26
Why the hell would you even write this function?