在以下示例中,我对Rust的行为感到困惑。
此示例失败:
let mut coll = vec![1, 2, 3].iter();
some_consuming_fn(&mut coll);
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:4:20
|
4 | let mut coll = vec![1, 2, 3].iter();
| ^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
5 | some_consuming_fn(&mut coll);
| --------- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
但是,如果将可迭代转换作为函数参数调用,则一切正常。
let coll = vec![1, 2, 3];
some_consuming_fn(&mut coll.iter());
我对已变成可迭代的集合的所有权规则感到困惑。为什么对some_iterable.iter()
的呼叫在被呼叫后立即中断?
供参考,some_consuming_fn
具有签名:
some_consuming_fn(x: &mut Iter<u32>) -> Foo;