Timmmm
Timmmm

Reputation: 96832

Modifying a slice of str's

I have a Vec<&str> and I want to remove a prefix from all of its elements. This is what I vaguely intend:

fn remove_prefix(v: &mut [&str], prefix: &str) {
    for t in v.iter_mut() {
        t = t.trim_left_matches(prefix);
    }
}

However I can't seem to get all the mut's in the right place. Or maybe it's a lifetime related thing? Can anyone give me a hint? Here is my current error:

makefile_to_qbs.rs:22:7: 22:34 error: mismatched types:
 expected `&mut &str`,
    found `&str`
(values differ in mutability) [E0308]
makefile_to_qbs.rs:22           t = t.trim_left_matches(prefix);

Upvotes: 5

Views: 623

Answers (1)

Chris Morgan
Chris Morgan

Reputation: 90832

t is of type &mut &str, a mutable pointer to a string slice. You wish to alter what the mutable reference points to, so you need to store a &str in *t.

fn remove_prefix(v: &mut [&str], prefix: &str) {
    for t in v.iter_mut() {
        *t = t.trim_left_matches(prefix);
    }
}

Upvotes: 6

Related Questions