Rust 锈:“是的。”;。。“活得不够长”;

Rust 锈:“是的。”;。。“活得不够长”;,rust,scope,lifetime,Rust,Scope,Lifetime,以下是代码(初学者有一定难度): 不确定我是否理解它,因为refcell是通过引用传递的(由\u matcher借用) 不确定我是否理解它,因为refcell是通过引用传递的(由_matcher借用) 问题是您正在定义Matcher,以便RefCell的生存期和RefCell内容的生存期必须相同 这意味着你要告诉rustcRefCell必须和它所包含的一样长,这意味着一旦你把RefCell放入匹配器中。。。您的程序不能再工作了,因为容器不能正确地超过其内容 您需要拆分您的生命周期,以便rustc

以下是代码(初学者有一定难度):

不确定我是否理解它,因为
refcell
是通过引用传递的(由
\u matcher
借用)

不确定我是否理解它,因为refcell是通过引用传递的(由_matcher借用)

问题是您正在定义
Matcher
,以便
RefCell
的生存期和
RefCell
内容的生存期必须相同

这意味着你要告诉rustc
RefCell
必须和它所包含的一样长,这意味着一旦你把
RefCell
放入
匹配器中
。。。您的程序不能再工作了,因为容器不能正确地超过其内容

您需要拆分您的生命周期,以便rustc知道它们是如何嵌套的,至少您需要为
&RefCell
及其内容赋予不同的生命周期,并告诉rustc内容比
&RefCell
的生命周期长:

pub结构匹配器{
发布索引:&'a RefCell
}
自我暗示{
匹配器{
指数
}
}
}

拆分
TIndex
的生存期参数和
TIndex
的生存期界限(TIndex的内容应该比TIndex的寿命长),这可能也是一个好主意,但对于您在此处发布的复制,似乎没有必要这样做。

这是否意味着每次我们都会引用某个东西('a here')它接受生存期(这里的内容是“b”),我们需要分离生存期?几乎是的,尽管它也是在该生存期参数化的容器的一个因素。如果添加了一个新的参数化结构,其中引用了
Matcher
,这是否意味着也应该添加一个新的生存期,例如
pub-struct-CombinedMatcher
use std::cell::RefCell;
use std::collections::HashMap;

pub trait TIndex<'a> {
    // cut
}

pub struct HashMapIndex<'a> {
    pub filter_by_keyword: HashMap<String, &'a str> // simplified (and ugly)
}

impl<'a> TIndex<'a> for HashMapIndex<'a> {
    // cut
}

pub struct Matcher<'a> {
    pub index: &'a RefCell<Box<dyn TIndex<'a> + 'a>>
}

impl<'a> Matcher<'a> {
    pub fn new(index: &'a RefCell<Box<dyn TIndex<'a> + 'a>>) -> Self {
        Matcher {
            index
        }
    }
}

pub fn main() {
    let index = HashMapIndex {
        filter_by_keyword: HashMap::new()
    };
    let boxed_index: Box<dyn TIndex> = Box::new(index);
    let refcell = RefCell::from(boxed_index);
    let mut _matcher = Matcher::new(
        &refcell // `refcell` does not live long enough
    );
}
    }
    | -
    | |
    | `refcell` dropped here while still borrowed
    | borrow might be used here, when `refcell` is dropped and runs the destructor for type `RefCell<Box<dyn TIndex<'_>>>`