i have code below,
enum List<'a> {
Cons(i32, Box<&'a List<'a>>),
Nil,
};
let list= Cons(10, Box::new(&Nil));
let lista = Cons(5, Box::new(&Cons(10, Box::new(&Nil))));
match lista {
Cons(x,_) => println!("{}",x),
Nil => ()
}
after running the code, the compiler says
21 | let lista = Cons(5, Box::new(&Cons(10, Box::new(&Nil))));
| ^^^^^^^^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
i can understand 'Cons(10, Box::new(&Nil))' is freed, so it goes wrong. but when i replace list with lista after match, eg:
match list {
Cons(x,_) => println!("{}",x),
Nil => ()
}
i think Nil is also a temporary value and dropped at the end of statement, but it runs well, what's the difference between list and lista?
` (or `&'a List<'a>` if you want [on-stack](https://rust-unofficial.github.io/too-many-lists/infinity-stack-allocated.html) or bump-allocated lists.) In any case, have a look at the [Too Many Lists](https://rust-unofficial.github.io/too-many-lists/index.html) book, if that's not what you're doing already.
– Caesar Feb 02 '23 at 06:27