【发布时间】:2017-07-29 18:29:44
【问题描述】:
代码:
use std::collections::HashSet;
use std::{mem, ptr, fmt};
use std::ops::Deref;
enum Unsafety {
Normal
}
enum ImplPolarity { Positive }
struct TraitRef;
struct Ty;
struct ImplItem;
enum ItemKind {
Impl(Unsafety,
ImplPolarity,
Option<TraitRef>, // (optional) trait this impl implements
Box<Ty>, // self
),
}
struct Item {
node: ItemKind,
}
pub struct P<T: ?Sized> {
ptr: Box<T>
}
impl<T: 'static> P<T> {
pub fn unwrap(self) -> T {
*self.ptr
}
}
impl<T: ?Sized> Deref for P<T> {
type Target = T;
fn deref(&self) -> &T {
&self.ptr
}
}
fn main() {
let mut items = Vec::<P<Item>>::new();
let mut item2: Item;
for item in items.drain(..) {
if let ItemKind::Impl(Unsafety::Normal,
ImplPolarity::Positive,
Some(ref trait_type),
ref for_type) = item.node {
} else {
// item2 = *item; // AAA
item2 = item.unwrap(); // BBB
}
}
}
产生编译时错误:
error[E0505]: cannot move out of `item` because it is borrowed
--> /home/xxx/.emacs.d/rust-playground/at-2017-07-29-204629/snippet.rs:64:21
|
61 | ref for_type) = item.node {
| ---- borrow of `item` occurs here
...
64 | item2 = item.unwrap();
我不明白两件事:
为什么它抱怨
if分支中的借用,而我们在else分支中?它们应该是相互排斥的,借用一个不应影响另一个。如果我将
let mut items = Vec::<P<Item>>::new();中的Vec替换为Vec<Box<Item>>并取消注释行AAA和注释行BBB,那么它会编译。Box和P都实现了Deref,所以item.node表达式应该是一样的。
【问题讨论】:
-
您的第一个问题已经得到解答 - If let borrow conundrum。请从您的问题中删除它。这是why you should only ask one question per question。
标签: rust