Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String append, cannot move out of dereference of '&'pointer

Tags:

rust

I'm having trouble combining two strings, I'm very new to rust so If there is an easier way to do this please feel free to show me.

My function loops through a vector of string tuples (String,String), what I want to do is be able to combine these two strings elements into one string. Here's what I have:

for tup in bmp.bitmap_picture.mut_iter() {
    let &(ref x, ref y) = tup;
    let res_string = x;
    res_string.append(y.as_slice());
}

but I receive the error : error: cannot move out of dereference of '&'-pointer for the line: res_string.append(y.as_slice());

I also tried res_string.append(y.clone().as_slice()); but the exact same error happened, so I'm not sure if that was even right to do.

like image 366
Syntactic Fructose Avatar asked Dec 11 '22 04:12

Syntactic Fructose


1 Answers

The function definition of append is:

fn append(self, second: &str) -> String

The plain self indicates by-value semantics. By-value moves the receiver into the method, unless the receiver implements Copy (which String does not). So you have to clone the x rather than the y.

If you want to move out of a vector, you have to use move_iter.

There are a few other improvements possible as well:

let string_pairs = vec![("Foo".to_string(),"Bar".to_string())];

// Option 1: leave original vector intact
let mut strings = Vec::new();
for &(ref x, ref y) in string_pairs.iter() {
    let string = x.clone().append(y.as_slice());
    strings.push(string);
}

// Option 2: consume original vector
let strings: Vec<String> = string_pairs.move_iter()
    .map(|(x, y)| x.append(y.as_slice()))
    .collect();
like image 198
A.B. Avatar answered Feb 03 '23 14:02

A.B.