Hello! I installed rust compiler yesterday. And see strange thing. I can return string reference but I can't return reference of another types. Is it possible to return int reference or custom struct reference?
fn get<'a>() -> &'a str {
let var = "my data";
var
}
This code can be compiled.
fn get<'a>() -> &'a i32 {
let var = 1;
var
}
But this code can't be compiled. And same for struct instance.
"my data" is, in fact, already a reference to a statically-allocated string constant; it has type &'static str, which is a subtype of &'a str for any 'a.
You needn't worry about that — if a function returns a big value, Rust converts it to rather take an output pointer and build the value there, sparing the copy. In any case, you can return a String which is essentially a smart pointer itself, to an array of values (UTF-8 bytes) rather than one value.
[quote="strake, post:7, topic:10051"]
You needn't worry about that — if a function returns a big value, Rust converts it to rather take an output pointer and build the value there, sparing the copy.
[/quote] Can you give me a link to material about this, please?
The optimization name would be N(amed)R(eturn)V(alue)O(ptimization), i.e. NRVO (or just RVO for returning temporaries). It may or may not occur though, so there's no guarantee that the copy will be avoided. But, with things like this, it's best to not worry about the (possible) copy until you see (i.e. profile) that it's a problem.
Whoops, missed your response until now. Yes, as @vitalyd says, it is RVO. And if the copy is not elided, i believe that qualifies as a deficiency of rustc and you ought to file a ticket.