【问题标题】:How Can I return refenrece of RefCell value [duplicate]如何返回 RefCell 值的参考 [重复]
【发布时间】:2021-04-27 13:54:10
【问题描述】:

我正在实施双向链表来学习 rust。
要获得双向链表值,
我想返回对值的引用。

如果我只返回值,我可以。
但如果我这样做,列表值必须实现Clone trait...
我该怎么办?

这是我的示例代码。

use std::rc::Rc;
use std::cell::RefCell;

struct Person{
    age: Rc<RefCell<i32>>,
}

impl Person {
    fn get_string<'a>(&'a self) -> &'a i32{
        //  acutually do while loop until reach designated index
        let person_age = *self.age.borrow_mut();
        //  I want to return reference to i32
        &person_age
    }
}
fn main() {
    let age = Rc::new(RefCell::new(10));
    let person = Person{age:Rc::clone(&age)};
    println!("person name is {}", person.get_string());
}

【问题讨论】:

    标签: rust


    【解决方案1】:

    您应该将Ref 作为RefCell do 返回

        fn get_string(&self) -> Ref<i32>{
            return self.age.borrow_mut()
        }
    

    除了它实现了 Drop 之外,它的行为应该或多或少类似于引用。它用于 RefCell 而不是引用,因为它确实可以维护 RefCell 不变量,因此当您使用 RefCell 时,您应该使用它。

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2015-08-30
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多