Function returning a String, does it copy the value?


#1

Assuming the following code:

fn main() {
    println!("I can show you {}", what02());
}

fn what02() -> String {
    let mut what = "the".to_string();
    what.push_str(" world. - 2.");
    what
}

Is what02() returns, is the value of the String copied before println! does its thing? Or since the String is about to go out of context, is the compiler able to reuse that that memory that was already initialised?


#2

For any kind of value, including function results, Rust uses move semantics by default. Copy semantics must be explicitly enabled by implementing the Copy trait, which String does not do, or by calling the clone() method.

As a consequence, the code which you’re showing will not copy the string. At best it will directly create it in the caller’s stack frame, at worst it will move it there by copying a pointer.


#3

Minor nit: it’s slightly more than a pointer since a String is basically a (ptr, capacity, len) tuple (it’s a Vec<u8>).