I am studying Rust right now. I want to test my understanding of property in rust. I get confused with the concepts of ownership and borrowing in a recursive structure. I see this code at rustbyexample.com
use List::{Cons, Nil};
enum List {
Cons(u32, Box<List>),
Nil,
}
impl List {
fn new() -> List {
Nil
}
fn prepend(self, elem: u32) -> List {
Cons(elem, Box::new(self))
}
fn len(&self) -> u32 {
match *self {
Cons(_, ref tail) => 1 + tail.len(),
Nil => 0
}
}
fn stringify(&self) -> String {
match *self {
Cons(head, ref tail) => {
format!("{}, {}", head, tail.stringify())
},
Nil => {
format!("Nil")
},
}
}
}
fn main() {
let mut list = List::new();
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);
println!("linked list has length: {}", list.len());
println!("{}", list.stringify());
}
How to visualize a stack and a bunch of this code?
From what I learned, I prependget ownership of the list, allocate space in the heap, and translate the list into the heap. When it prependfinishes, it moves (gives ownership) the newly created list to an external variable.
Is this visualization correct?
The first list is :: new return Nil, so the stack will contain Nil.
After executing list.prepend (1), Nil will be on the heap at the address 0x0000 (assumption), Cons (1,0x0000) will enter the stack.
list.prepend(2) Cons (1,0x0000) 0x00002 (), Cons (2,0x0002).
, list.prepend(3) Cons (2,0x0002), 0x00004 (), Cons (3,0x0004).
Cons (1,0x0000)? Is Cons (2,0x0002) Cons (1,0x0000)? ?
, , , Rust , . ?