3

I was reading rust book when I came across this:

fn main() {
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used
}

as it turns out 'The + operator uses the add method, whose signature looks something like this':

fn add(self, s: &str) -> String { // ... }

I understand the reason why s1 is 'consumed' and is no longer available later. But why does rust do this? I mean, why can't add method have reference to self (&self) as a first parameter, so that s1 string will be available for later use?

1 Answer 1

8

If the signature was fn add(&self, s:&str) this would mean that, even if in the calling context the first parameter (known as self) could be consumed (because not used any more afterwards), the add() function would have to start by cloning this string in order to extend it with s.

On the other hand, using a value for self enables the reuse of the original string to extend it directly without cloning.

This situation is at the same time the most efficient and the most general because if you really want to preserve the original string you can always clone it before the call to add().

fn main() {
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1 + &s2;
    // println!("s1: {}", s1); // borrow of moved value: `s1`
    println!("s2: {}", s2);
    println!("s3: {}", s3);
    println!("~~~~~~~~~~~~~~~~");
    let s1 = String::from("Hello, ");
    let s2 = String::from("world!");
    let s3 = s1.clone() + &s2;
    println!("s1: {}", s1); // not consumed by +
    println!("s2: {}", s2);
    println!("s3: {}", s3);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I understand now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.