这个问题在这里已有答案:
-
How do I borrow a RefCell<HashMap>, find a key, and return a reference to the result? [duplicate] 1回答
-
Why can't I store a value and a reference to that value in the same struct? 2个答案
我的目标是编写一个函数,它将 Rc<RefCell<&'a mut [u8]>>
作为参数并返回一个包含对内部切片的引用的结构,但我不能满足借用检查器 . 我的第一次尝试看起来像这样:
pub fn mk_buf_holder<'a>(buf: Rc<RefCell<&'a mut [u8]>>) -> BufHolder<'a> {
BufHolder::<'a> { buf: buf.borrow_mut().deref_mut()}
}
但是,这当然不起作用,因为 borrow_mut
的结果超出了范围 . 我的下一次尝试为结构添加了额外的成员,只是为了保持原本可能是暂时的值 . 我认为将它们放入结构中将使它们具有与_983143相同的生命周期,但借用检查器不同意 . 这是完整的例子:
use std::cell::{Ref, RefCell, RefMut};
use std::ops::DerefMut;
use std::rc::Rc;
pub struct BufHolder<'a> {
buf: &'a mut [u8],
bufclone: Rc<RefCell<&'a mut [u8]>>,
bufref: RefMut<'a, &'a mut[u8]>
}
pub fn mk_buf_holder<'a>(buf: Rc<RefCell<&'a mut [u8]>>) -> BufHolder<'a> {
let bufclone = buf.clone();
let bufref = bufclone.borrow_mut();
BufHolder::<'a> { bufclone: bufclone,
buf: bufref.deref_mut(),
bufref: bufref }
}
编译器仍然告诉我, borrow_mut()
的结果并不像编译器正在复制到输出中,而是移动它 . 我该如何修复这个功能?
error: `bufclone` does not live long enough
--> src/main.rs:13:18
|
13 | let bufref = bufclone.borrow_mut();
| ^^^^^^^^ does not live long enough
...
19 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the body at 11:74...
--> src/main.rs:11:75
|
11 | pub fn mk_buf_holder<'a>(buf: Rc<RefCell<&'a mut [u8]>>) -> BufHolder<'a> {
| ___________________________________________________________________________^ starting here...
12 | | let bufclone = buf.clone();
13 | | let bufref = bufclone.borrow_mut();
14 | | BufHolder::<'a> {
15 | | bufclone: bufclone,
16 | | buf: bufref.deref_mut(),
17 | | bufref: bufref,
18 | | }
19 | | }
| |_^ ...ending here
error: `bufref` does not live long enough
--> src/main.rs:16:14
|
16 | buf: bufref.deref_mut(),
| ^^^^^^ does not live long enough
...
19 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the body at 11:74...
--> src/main.rs:11:75
|
11 | pub fn mk_buf_holder<'a>(buf: Rc<RefCell<&'a mut [u8]>>) -> BufHolder<'a> {
| ___________________________________________________________________________^ starting here...
12 | | let bufclone = buf.clone();
13 | | let bufref = bufclone.borrow_mut();
14 | | BufHolder::<'a> {
15 | | bufclone: bufclone,
16 | | buf: bufref.deref_mut(),
17 | | bufref: bufref,
18 | | }
19 | | }
| |_^ ...ending here