I'm reading about Rc<T>
here, and can't understand, what it's all about. I'm understand the point of counter in languages, where we have to manually free memory. But Rust is different.
We use the
Rc<T>
type when we want to allocate some data on the heap for multiple parts of our program to read and we can’t determine at compile time which part will finish using the data last.
Problem is, there is no examples on page, which demonstrates this strength of Rc<T>
. And I can't imagine it for myself. I'm just learning. There is only this:
enum List {
Cons(i32, Rc<List>),
Nil,
}
use crate::List::{Cons, Nil};
use std::rc::Rc;
fn main() {
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));
}
There is also such statement:
The borrow checker wouldn’t let us compile
let a = Cons(10, &Nil);
for example, because the temporaryNil
value would be dropped beforea
could take a reference to it.
Well, borrow checker allows this for me:
enum List<'a> {
Cons(i32, &'a List<'a>),
Nil,
}
use List::{Cons, Nil};
fn example() {
let a = Cons(10, &Nil);
let a = Cons(5, &Cons(10, &Nil));
let b = Cons(3, &a);
let c = Cons(4, &a);
}
Maybe it differs in important way, but I can't see it, since I'm just try to repeat this simple example. I just can see, that it is compiles.