how to

rc

Jan 15, 2024
langsrust
1 Minutes
110 Words

Rc

rust 的函数参数类型为非引用时,将会吃掉参数的所有权。

当不需要 share 时,使用 Box,否则使用 Rc。

1
trait Output {
2
fn output(&self);
3
}
4
5
struct Foo {
6
x: i32,
7
}
8
9
impl Output for Foo {
10
fn output(&self) {
11
println!("{}", self.x);
12
}
13
}
14
15
fn func(v: &mut Vec<Rc<dyn Output>>) {
5 collapsed lines
16
let foo = Foo { x: 1 };
17
let bar = Bar { y: 2.0 };
18
v.push(Rc::new(foo));
19
v.push(Rc::new(bar));
20
}

神奇的是,Rc 可以直接调用 Type 的成员函数,我也不知道为什么。

Article title:rc
Article author:Julyfun
Release time:Jan 15, 2024
Copyright 2025
Sitemap