Struct Impl function value moved in previous iteration of loop


#1

I have created a struct (mp) which contains a couple of regexes (which are compiled when I init the struct so they don’t get recompiled each time), and the Impl for that struct has a function (parse) which uses those stored compiled regexes when processing lines of data. This works fine when I pass it one line of data. However, when I try to iterate through multiple lines of data, I get:

error[E0382]: use of moved value: `mp`
   --> src/main.rs:144:24
    |
144 |         let new_data = mp.parse(line);
    |                        ^^^ value moved here in previous iteration of loop
    |
    = note: move occurs because `mp` has type `MessageProcessor`, which does not implement the `Copy` trait

I don’t think that I should be using the Copy trait here, but even when I tried regex::Regex doesn’t support Copy anyway. The for loop I am using is:

    for line in &lines {
        let new_data = mp.parse(line);
        println!("data {:?}", new_data);
    }

I haven’t implemented any lifetimes, and have tried amp.parse and also &amp.parse. There is nothing mutable in the struct itself (just a container for the regexes and the parsing function). I can’t understand why mp is moving here.
Thanks in advance for any assistance.


#2

What is the signature of parse? It should be fn parse(&self, &str line). Note the &.


#3

Thanks @matklad - I looked at the function pub fn parse(self, data: &str) -> Message {} which was missing the & to self! Changed it to pub fn parse(&self, data: &str) -> Message {} and it’s now working!