简体   繁体   中英

How do I borrow an Iterator?

I have a piece of code that I'm using that I found in another Stack Overflow question

fn is_palindromic(num: i64) -> bool {
    let string = num.to_string();
    let bytes = string.as_bytes();
    let iter = bytes.iter();
    let n = bytes.len() / 2;
    equals(iter.take(n), iter.rev().take(n))
}

This worked fine when I originally found it, but something changed in the Rust nightlies between 1/30/15 and 2/17/12 that caused this new error to pop up:

src/program.rs:8:26: 8:30 error: use of moved value: `iter`
src/program.rs:8     equals(iter.take(n), iter.rev().take(n))
                                          ^~~~
src/program.rs:8:12: 8:16 note: `iter` moved here because it has type `core::slice::Iter<'_, u8>`, which is non-copyable
src/program.rs:8     equals(iter.take(n), iter.rev().take(n))
                            ^~~~

I've looked through the documentation, but I can't seem to find anything that indicates what might have changed. It seems like maybe the take method now behaves differently, but I'm not really sure how to solve the situation short of cloning bytes and using two separate iterators.

This seems like a really inefficient way of solving what seems like a pretty common problem, so I'm thinking I may be missing something.

What is the correct method of borrowing an iterator for use with methods like std::iter::order::equals ?

You don't need to clone the underlying data ( bytes ), but you do need to clone the iterator:

fn is_palindromic(num: i64) -> bool {
    let string = num.to_string();
    let bytes = string.as_bytes();
    let iter = bytes.iter();
    let n = bytes.len() / 2;
    equals(iter.clone().take(n), iter.rev().take(n))
}

The iterator isn't implicitly Copy -able, so you need to explicitly Clone it.

This changed in this commit , when IntoIterator was introduced :

This PR also makes iterator non-implicitly copyable, as this was source of subtle bugs in the libraries. You can still use clone() to explictly copy the iterator.

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM