【问题标题】:How to pass lines() iterator as an argument to a function, in a loop如何在循环中将 lines() 迭代器作为参数传递给函数
【发布时间】:2021-11-28 11:01:07
【问题描述】:

这里是开始:

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

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

这里是 read_1_sequence 函数:

    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.

但是,如果对 read_1_sequence 的调用处于循环中,如下所示:

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

我收到(显然)消息:

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

有解决办法吗?感谢您的任何提示。

祝你(编程)愉快!

【问题讨论】:

    标签: function loops rust iterator arguments


    【解决方案1】:

    其他答案建议克隆lines,但这不起作用,因为Lines 没有实现Clone(如果实现了,它可能会在每个循环中从文件开头重新开始) .相反,您应该更改您的功能以采用&amp;mut Lines&lt;B&gt;

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

    然后这样称呼它:

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

    【讨论】:

    • 太好了,非常感谢,它有效!而且它仍然很简单......也一次又一次地感谢 Stackoverflow。
    • 如果它解决了您的问题,您能否将其标记为已解决(通过单击答案左侧的复选框使其变为绿色)以便其他有相同问题的人知道?
    猜你喜欢
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    相关资源
    最近更新 更多