gpt4 book ai didi

rust - 如果可能,我是否应该避免在Rust中使用Rc和RefCell?

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

Rust会在编译时提供借入支票。但是,如果使用RcRefCell,则将在运行时推迟检查,并且在程序违反规则时会引发 panic 。像这样:

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

fn func1(reference: Rc<RefCell<String>>){
let mut a = reference.borrow_mut();
*a = String::from("func1");
func2(reference.clone());
}

fn func2(reference: Rc<RefCell<String>>){
let mut a = reference.borrow_mut();
*a = String::from("func2");
func3(reference.clone());
}

fn func3(reference: Rc<RefCell<String>>){
let mut a = reference.borrow_mut();
*a = String::from("func3");
}


fn main() {
let a = Rc::new(RefCell::new(String::from("hello")));
func1(a.clone());
}

这段代码仍将错误(可能不是错误)留给运行时并感到 panic 。所以我应该避免尽可能多地使用 RcRefCell吗?并将此代码算作安全代码吗?

最佳答案

由于RcRefCell允许您编译在运行时可能出现紧急情况的代码,因此请不要轻易使用它们。您可以使用try_borrow_mut而不是borrow_mut来避免出现 panic 并自行处理结果。
话虽如此,即使您阻止所有 panic ,RcRefCell在运行时也要付出代价,因为它们保留了一个引用计数器。在许多情况下,可以通过以更使用rust 的方式重写代码来避免它们。

fn func1(mut string: String) -> String {
string = "func1".into();
func2(string)
}

fn func2(mut string: String) -> String {
string = "func2".into();
func3(string)
}

fn func3(string: String) -> String {
"func3".into()
}

fn main() {
let a = func1("hello".into());
}

更简单,更安全。 Rust会为您进行优化。
要回答您的最后一个问题,将 borrow_mut视为不安全的代码,因为即使使用 #![forbid(unsafe_code)]指令,该代码也可以编译

关于rust - 如果可能,我是否应该避免在Rust中使用Rc和RefCell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65338749/

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