标签:4.5 Cons Reference clone value references Rc data rust
Rc<T>
, the Reference Counted Smart Pointer
In the majority of cases, ownership is clear: you know exactly which variable owns a given value. However, there are cases when a single value might have multiple owners. For example, in graph data structures, multiple edges might point to the same node, and that node is conceptually owned by all of the edges that point to it. A node shouldn’t be cleaned up unless it doesn’t have any edges pointing to it.
To enable multiple ownership, Rust has a type called Rc<T>
, which is an abbreviation for reference counting. The Rc<T>
type keeps track of the number of references to a value to determine whether or not the value is still in use. If there are zero references to a value, the value can be cleaned up without any references becoming invalid.
Note that Rc<T>
is only for use in single-threaded scenarios.
Using Rc<T>
to Share Data
Each Cons
variant will now hold a value and an Rc<T>
pointing to a List
.
When we create b
, instead of taking ownership of a
, we’ll clone the Rc<List>
that a
is holding, thereby increasing the number of references from one to two and letting a
and b
share ownership of the data in that Rc<List>
.
use std::rc::Rc; pub enum List { Cons(i32, Rc<List>), Nil, } use crate::base::l1_rc::List::{Cons, Nil}; pub fn test() { let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); let b = Cons(3, Rc::clone(&a)); let c = Cons(4, Rc::clone(&a)); }
We’ll also clone a
when creating c
, increasing the number of references from two to three.
Every time we call Rc::clone
, the reference count to the data within the Rc<List>
will increase, and the data won’t be cleaned up unless there are zero references to it.
We could have called a.clone()
rather than Rc::clone(&a)
, but Rust’s convention is to use Rc::clone
in this case. The implementation of Rc::clone
doesn’t make a deep copy of all the data like most types’ implementations of clone
do. The call to Rc::clone
only increments the reference count, which doesn’t take much time. Deep copies of data can take a lot of time.
标签:4.5,Cons,Reference,clone,value,references,Rc,data,rust 来源: https://www.cnblogs.com/perfei/p/15809204.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。