【发布时间】:2017-05-31 16:06:30
【问题描述】:
use std::borrow::BorrowMut;
trait Foo {}
struct Bar;
impl Foo for Bar {}
fn main() {
let mut encryptor: Box<Foo> = Box::new(Bar);
encrypt(encryptor.borrow_mut());
}
fn encrypt(encryptor: &mut Foo) { }
但它失败并出现此错误:
error: `encryptor` does not live long enough
--> src/main.rs:11:1
|
10 | encrypt(encryptor.borrow_mut());
| --------- borrow occurs here
11 | }
| ^ `encryptor` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
#rustbeginners 的好心人发现我必须取消引用框才能获取内容,然后借用内容。 Like this:
trait Foo {}
struct Bar;
impl Foo for Bar {}
fn main() {
let mut encryptor: Box<Foo> = Box::new(Bar);
encrypt(&mut *encryptor);
}
fn encrypt(encryptor: &mut Foo) { }
有效,但我不明白。
为什么我需要先取消引用?试图说的错误是什么?通常,在函数末尾删除值不是错误。
显然,不只是我不明白这是如何工作的;一个issue has been filed。
【问题讨论】:
-
请注意,您甚至不需要调用
encrypt来获取此错误;只是试图通过borrow_mut创建一个独立的可变引用会失败。
标签: rust traits borrow-checker