Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

rust所有权问题

我想让Handbag take方法 返回articke 中数据的所有权 并设置为None 这个编译器都不通过 (⊙﹏⊙)晕(((φ(◎ロ◎;)φ)))

struct Handbag<T> {
    article: Option<Box<T>>,
}
impl <T>Handbag<T> {
    fn new() -> Handbag<T> {
        Handbag{
            article:None,
        }
    }
    fn put(&mut self,article: T) {
        self.article = Some(Box::new(article));
    }
    fn take(&mut self) -> Option<Box<T>> {
        match &self.article {
            Some(data) => { // data: &Box<T>
                self.article = None;
                return Some(*data)
            },
            None => None,
        }
    }
}

fn main() {
    let mut handbag = Handbag::new();
    handbag.put(String::from("hello"));
    if let Some(article) = handbag.take() {
        println!("data: {}",article);
    }

    println!("Hello, world!");
}

err out:

error[E0506]: cannot assign to `self.article` because it is borrowed
  --> src/main.rs:16:17
   |
14 |         match &self.article {
   |               ------------- borrow of `self.article` occurs here
15 |             Some(data) => {
16 |                 self.article = None;
   |                 ^^^^^^^^^^^^ assignment to borrowed `self.article` occurs here
17 |                 return Some(*data)
   |                             ----- borrow later used here

error[E0507]: cannot move out of `*data` which is behind a shared reference
  --> src/main.rs:17:29
   |
17 |                 return Some(*data)
   |                             ^^^^^ move occurs because `*data` has type `std::boxed::Box<T>`, which does not implement the `Copy` trait

error: aborting due to 2 previous errors

Some errors have detailed explanations: E0506, E0507.
For more information about an error, try `rustc --explain E0506`.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

take方法直接返回self.article.take()就行了


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...