# Rust RC T用法解析

## 本文概述

• Rc <T>代表引用计数智能指针。
• Rc <T>智能指针会跟踪对某个值的引用数, 以确定该值是否仍在使用中, 并且如果某个值的引用为零, 则可以清除该值。
• Rc <T>智能指针是单线程引用计数指针。

## 使用Rc <T>共享数据

``````enum List
{
Cons(i32, Box<List>), Nil, }
use List::{Cons, Nil};
fn main()
{
let a = Cons(10, Box::new(Cons(15, Box::new(Nil))));
let b = Cons(2, Box::new(a));
let c = Cons(1, Box::new(a));
}``````

## 如何克服这个问题

``````enum List
{
Cons(i32, Rc<List>), Nil, }
use List::{Cons, Nil};
use std::rc::Rc;
fn main()
{
let a = Rc::new(Cons(10, Rc::new(Cons(15, Rc::new(Nil)))));
let b = Cons(2, Rc::clone(&a));
let c = Cons(1, Rc::clone(&a));
}``````

## 克隆Rc <T>会增加引用计数

``````enum List
{
Cons(i32, Rc<List>), Nil, }
use List::{Cons, Nil};
use std::rc::Rc;
fn main()
{
let a = Rc::new(Cons(10, Rc::new(Cons(15, Rc::new(Nil)))));
println!("Reference count after creating a List : {}", Rc::strong_count(&a));
let b = Cons(2, Rc::clone(&a));
println!("Reference count after creating b List : {}", Rc::strong_count(&a));
{
let c = Cons(1, Rc::clone(&a));
println!("Reference count after creating c List : {}", Rc::strong_count(&a));
}
println!("Reference count when c goes out of the scope : {}", Rc::strong_count(&a));
}``````

``````Reference count after creating a List : 1
Reference count after creating b List : 2
Reference count after creating c List : 3
Reference count when c goes out of the scope : 2``````

• 回顶