rustlings

solving rustlings ft. dracuxan
git clone [email protected]:dracuxan/rustlings.git
Log | Files | Refs

box1.rs (1419B)


      1 // At compile time, Rust needs to know how much space a type takes up. This
      2 // becomes problematic for recursive types, where a value can have as part of
      3 // itself another value of the same type. To get around the issue, we can use a
      4 // `Box` - a smart pointer used to store data on the heap, which also allows us
      5 // to wrap a recursive type.
      6 //
      7 // The recursive type we're implementing in this exercise is the "cons list", a
      8 // data structure frequently found in functional programming languages. Each
      9 // item in a cons list contains two elements: The value of the current item and
     10 // the next item. The last item is a value called `Nil`.
     11 
     12 // TODO: Use a `Box` in the enum definition to make the code compile.
     13 #[derive(PartialEq, Debug)]
     14 enum List {
     15     Cons(i32, List),
     16     Nil,
     17 }
     18 
     19 // TODO: Create an empty cons list.
     20 fn create_empty_list() -> List {
     21     todo!()
     22 }
     23 
     24 // TODO: Create a non-empty cons list.
     25 fn create_non_empty_list() -> List {
     26     todo!()
     27 }
     28 
     29 fn main() {
     30     println!("This is an empty cons list: {:?}", create_empty_list());
     31     println!(
     32         "This is a non-empty cons list: {:?}",
     33         create_non_empty_list(),
     34     );
     35 }
     36 
     37 #[cfg(test)]
     38 mod tests {
     39     use super::*;
     40 
     41     #[test]
     42     fn test_create_empty_list() {
     43         assert_eq!(create_empty_list(), List::Nil);
     44     }
     45 
     46     #[test]
     47     fn test_create_non_empty_list() {
     48         assert_ne!(create_empty_list(), create_non_empty_list());
     49     }
     50 }