You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
So how do we solve this problem? There are two approaches we can take. The first is making a copy rather than using a reference:
fnmain(){letmut x = vec!["Hello","world"];let y = x[0].clone();
x.push("foo");}
Rust has move semantics by default, so if we want to make a copy of some data, we call the clone() method. In this example, y is no longer a reference to the vector stored in x, but a copy of its first element, "Hello". Now that we don’t have a reference, our push() works just fine.
The type of x is Vec<&'static str>. It's not necessary to clone anything here, because reference types are Copy. Even calling x[0].clone() is just copying the pointer into y, not making a copy of the string.