4
votes

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.

2

2 Answers

9
votes

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();
4
votes

It seems like you might be confusing append, which takes the receiver by value and returns itself, with push_str, which simply mutates the receiver (passed by mutable reference) as you seem to expect. So the simplest fix to your example is to change append to push_str. You'll also need to change "ref x" to "ref mut x" so it can be mutated.