Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the string literal not moved?

Tags:

rust

ownership

I was going through Rust second edition ebook and in a piece of code from the linked chapter, if I remove the reference operator (&) in line 3, the program still works perfectly fine.

let mut s1 = String::from("foo");
let s2 = "bar";
s1.push_str(&s2); // here
println!("s2 is {}", s2);

The value of s2 should be moved as per the book. However, if I change

s1.push_str(&s2);

to

s1.push_str(s2);

the following line should trigger an error, but it doesn't happen:

println!("s2 is {}", s2);

A fragment from the documentation:

Listing 8-16: Using a string slice after appending its contents to a String If the push_str method took ownership of s2 , we wouldn’t be able to print out its value on the last line. However, this code works as we’d expect!

I am using Rust 1.24.1.

like image 900
Kajal Sinha Avatar asked Oct 21 '25 21:10

Kajal Sinha


1 Answers

The signature of push_str is:

pub fn push_str(&mut self, string: &str)

Which means its argument is a reference. This matches the type of s2, which is a reference to a static string slice:

let s2: &'static str = "bar";

The compiler is able to dereference the argument of push_str as much as necessary, so s1.push_str(s2) works just as well as s1.push_str(&&&&&s2).

Since in the end you are always passing a reference, the argument is not moved (only borrowed), and s2 is still available after it is pushed.

like image 116
ljedrz Avatar answered Oct 24 '25 15:10

ljedrz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!