Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why can't I concat the same string twice in rust

Hi as seen in the Rust Book you can use clone to set s2 to s1 like this

let s1 = String::from("hello");
    let s2 = s1.clone();

    println!("s1 = {}, s2 = {}", s1, s2);

Why can’t I change s2 to be s1.clone() + s1.clone()

let s1 = String::from("hello");
    let s2 = s1.clone()+ s1.clone();

    println!("s1 = {}, s2 = {}", s1, s2);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The Add instance for strings takes a String on the left and a &str on the right. This consumes the string on the left and extends it with (a copy of) the string on the right. It does this for efficiency reasons, to avoid having to copy both strings in every case.

So when you want to concatenate two strings in Rust with +, the left-hand side needs to be a String (an owned string) and the right-hand side needs to be a &str (a borrowed string slice). So consider

let s2 = s1.clone() + &s1.clone();

or, since we’re borrowing it, there’s no need for the second clone at all.

let s2 = s1.clone() + &s1;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading