Returning reference


#1

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.


#2

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

EDIT:
This, for example, is legal:

static n: i32 = 1;
fn get<'a>() -> &'a i32 { &n }

or equivalently:

static n: i32 = 1;
fn get() -> &'static i32 { &n }

#3

Does it mean str variables live as long as a static variable? Can you give me link to page where I can read about this?


#4

str literals do live as long as static variables, but not all str variables (they could be references into String objects).


#5

What should I do if I need to return object without copying? Is it possible only using Box (smart pointer)?


#6

Oh sorry, I have found information about &str in RustBook.


#7

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.


#8

I don’t why, but I didn’t find this topic early. It covers my question. Thank you.


#9

[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?


#10

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.


#11

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.