rustlings/exercises/19_smart_pointers/box1.rs

51 lines
1.4 KiB
Rust
Raw Normal View History

// At compile time, Rust needs to know how much space a type takes up. This
// becomes problematic for recursive types, where a value can have as part of
// itself another value of the same type. To get around the issue, we can use a
// `Box` - a smart pointer used to store data on the heap, which also allows us
// to wrap a recursive type.
2020-05-26 21:46:24 +01:00
//
2024-06-28 20:24:35 +01:00
// The recursive type we're implementing in this exercise is the "cons list", a
// data structure frequently found in functional programming languages. Each
2024-06-28 20:24:35 +01:00
// item in a cons list contains two elements: The value of the current item and
// the next item. The last item is a value called `Nil`.
2020-05-26 21:46:24 +01:00
2024-06-28 20:24:35 +01:00
// TODO: Use a `Box` in the enum definition to make the code compile.
2020-05-26 21:46:24 +01:00
#[derive(PartialEq, Debug)]
2024-05-22 14:04:12 +01:00
enum List {
2020-05-26 21:46:24 +01:00
Cons(i32, List),
Nil,
}
2024-06-28 20:24:35 +01:00
// TODO: Create an empty cons list.
2024-05-22 14:04:12 +01:00
fn create_empty_list() -> List {
todo!()
2020-05-27 10:03:59 +01:00
}
2024-06-28 20:24:35 +01:00
// TODO: Create a non-empty cons list.
2024-05-22 14:04:12 +01:00
fn create_non_empty_list() -> List {
todo!()
2020-05-27 10:03:59 +01:00
}
2024-06-28 20:24:35 +01:00
fn main() {
println!("This is an empty cons list: {:?}", create_empty_list());
println!(
"This is a non-empty cons list: {:?}",
create_non_empty_list(),
);
}
2020-05-27 10:03:59 +01:00
#[cfg(test)]
mod tests {
use super::*;
2020-05-26 21:46:24 +01:00
2020-05-27 10:03:59 +01:00
#[test]
fn test_create_empty_list() {
2024-06-28 20:24:35 +01:00
assert_eq!(create_empty_list(), List::Nil);
2020-05-27 10:03:59 +01:00
}
2020-05-26 21:46:24 +01:00
2020-05-27 10:03:59 +01:00
#[test]
fn test_create_non_empty_list() {
2024-05-22 14:13:18 +01:00
assert_ne!(create_empty_list(), create_non_empty_list());
2020-05-27 10:03:59 +01:00
}
2020-05-26 21:46:24 +01:00
}