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`.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
take方法直接返回self.article.take()就行了