Laurent Bloch
Laurent Bloch

Reputation: 65

How to pass lines() iterator as an argument to a function, in a loop

Here is the beginning:

    let fb = BufReader::new(&f);
    let lines = fb.lines();

        let bank_sequence = read_1_sequence(&mut count, lines);
        print_seq(&bank_sequence);

and here the read_1_sequence function :

    fn read_1_sequence<B: BufRead>(count: &mut u8, lines: Lines<B>)
// ...

    for line in lines {
        let the_line = line.unwrap();
        if the_line.len() > 0 {
        let first = &the_line[0..1];
        if first == ">" {
// etc.

But, if the call to read_1_sequence is in a loop, like here:

    loop {
        let bank_sequence = read_1_sequence(&mut count, lines);
        print_seq(&bank_sequence);
    }

I receive (obviously) the message:

26 |     let lines = fb.lines();
   |         ----- move occurs because `lines` has type `std::io::Lines<BufReader<&File>>`, which does not implement the `Copy` trait
...
29 |         let bank_sequence = read_1_sequence(&mut count, lines);
   |                                                         ^^^^^ value moved here, in previous iteration of loop

Is there a solution? Thanks for any hint.

Have a nice (programming) day!

Upvotes: 0

Views: 693

Answers (1)

Jmb
Jmb

Reputation: 23434

The other answers suggest cloning lines, but that won't work because Lines doesn't implement Clone (and if it did, it would probably start over from the beginning of the file in each loop). Instead you should change your function to take &mut Lines<B>:

fn read_1_sequence<B: BufRead>(count: &mut u8, lines: &mut Lines<B>)

and call it like this:

loop {
    let bank_sequence = read_1_sequence(&mut count, &mut lines);
    print_seq(&bank_sequence);
}

Upvotes: 4

Related Questions