Rust标准库中有几种包装类型:
std::cell模块中的单元格:Cell和RefCellRc和Arc.std::sync模块中的类型:Mutex或者AtomicBool例如据我了解,这些是包装器,提供了比简单参考更多的可能性.虽然我理解一些基础知识,但我看不到整体情况.
他们到底做了什么?细胞和参考计数家族是否提供正交或类似的特征?
您什么时候需要使用Cell或RefCell?似乎有许多其他类型选择适合代替这些,文档警告说使用RefCell是一种"最后的手段".
使用这些类型是" 代码味 "吗?任何人都可以展示一个例子,使用这些类型比使用其他类型更有意义,例如Rc甚至Box?
我正在学习Rust,我不明白为什么这不起作用.
#[derive(Debug)]
struct Node {
value: String,
}
#[derive(Debug)]
pub struct Graph {
nodes: Vec<Box<Node>>,
}
fn mk_node(value: String) -> Node {
Node { value }
}
pub fn mk_graph() -> Graph {
Graph { nodes: vec![] }
}
impl Graph {
fn add_node(&mut self, value: String) {
if let None = self.nodes.iter().position(|node| node.value == value) {
let node = Box::new(mk_node(value));
self.nodes.push(node);
};
}
fn get_node_by_value(&self, value: &str) -> Option<&Node> {
match self.nodes.iter().position(|node| node.value == *value) {
None => None, …Run Code Online (Sandbox Code Playgroud) 我正在努力学习Rust,但我唯一要做的就是不停地试图将熟悉(对我而言)Java概念塞进其类型系统中.或者尝试使用Haskell概念等.
我想写一个有Player很多Resources 的游戏.每个人Resource都可以拥有一个Player:
struct Player {
points: i32,
}
struct Resource<'a> {
owner: Option<&'a Player>,
}
fn main() {
let mut player = Player { points: 0 };
let mut resources = Vec::new();
resources.push(Resource {
owner: Some(&player),
});
player.points = 30;
}
Run Code Online (Sandbox Code Playgroud)
它不能编译,因为我不能将资源指向播放器,同时修改它:
error[E0506]: cannot assign to `player.points` because it is borrowed
--> src/main.rs:15:5
|
13 | owner: Some(&player),
| ------ borrow of `player.points` occurs here
14 | });
15 | player.points …Run Code Online (Sandbox Code Playgroud)