Rust tips @rust@octodon.social
Follow

uses types to automatically manage memory.

The owned `String` type tells the compiler to free it.
The borrowed `&str` tells the compiler NOT to free it.

But you can't mix them, because the compiler won't know whether to free the variable or not:

let label = if x != 0 {x.to_string()} else {"zero"};

The tip:

let tmp;
let label = if x != 0 {tmp = x.to_string(); &tmp} else {"zero"};

Now the compiler knows to free the `tmp`, but not the `label`.

Cow: is.gd/vi8eMF

· Web · 2 · 2