I have been reading Rust and Go in parallel and I see subtle differences in how both these languages deal with dangling pointers and the problems it causes. For example, here is a version in Rust:
fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -> &String {
let s = String::from("hello");
&s
}
The above would error out saying that in the function dangle
, s
goes out of scope and I cannot return a reference to it! But in Go, this seems to be sort of allowed?
How is such a thing handled in Go? Is it easy to create dangling pointers in Go? If so what measures do I have to control them?
In Go, dangling pointers are not a thing, due to the way how escape analysis works. Suppose you have a code like this:
func CreateUser(name string) *User {
return &User{Name: name}
}
The compiler will understand that because the pointer can be accessed after the function exits, the structure should be allocated on heap. As Effective Go says:
Note that, unlike in C, it's perfectly OK to return the address of a local variable; the storage associated with the variable survives after the function returns.
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