gpt4 book ai didi

rust - 如何返回 RefCell 值的引用

转载 作者:行者123 更新时间:2023-12-03 11:44:07 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How do I return a reference to something inside a RefCell without breaking encapsulation?

(3 个回答)



How to borrow the T from a RefCell<T> as a reference?

(1 个回答)



How can I obtain an &A reference from a Rc<RefCell<A>>?

(1 个回答)


去年关闭。




我正在实现双向链表来学习使用rust 。
要获得双向链表值,
我想返回对值的引用。
如果我只是返回值,我可以。
但如果我这样做,列表值必须实现 Clone特征...
我应该怎么做?
这是我的示例代码。

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());
}

最佳答案

您应该返回 Ref作为 RefCell do

    fn get_string(&self) -> Ref<i32>{
return self.age.borrow_mut()
}
除了它实现了 Drop 之外,它的行为应该或多或少类似于引用。它在 RefCell 中使用而不是引用,因为它确实可以维护 RefCell 不变量,因此当您使用 RefCell 时,您应该使用它。

关于rust - 如何返回 RefCell 值的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65856322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com