Skip to content

Commit 9ea72ed

Browse files
committed
// box1.rs
// // 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. // // The recursive type we're implementing in this exercise is the `cons list` - a // data structure frequently found in functional programming languages. Each // 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`. // // Step 1: use a `Box` in the enum definition to make the code compile // Step 2: create both empty and non-empty cons lists by replacing `todo!()` // // Note: the tests should not be changed // // Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint. // I AM NOT DONE #[derive(PartialEq, Debug)] pub enum List { // 用 Box 包装 List,将递归类型转为固定大小的指针 Cons(i32, Box<List>), Nil, } fn main() { println!("This is an empty cons list: {:?}", create_empty_list()); println!( "This is a non-empty cons list: {:?}", create_non_empty_list() ); } pub fn create_empty_list() -> List { // 空列表直接返回 Nil 变体 List::Nil } pub fn create_non_empty_list() -> List { // 非空列表:嵌套 Cons 结构,最后用 Box::new(Nil) 终止递归 List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil)))) } #[cfg(test)] mod tests { use super::*; #[test] fn test_create_empty_list() { assert_eq!(List::Nil, create_empty_list()) } #[test] fn test_create_non_empty_list() { assert_ne!(create_empty_list(), create_non_empty_list()) } }
1 parent b702acf commit 9ea72ed

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

exercises/smart_pointers/box1.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222

2323
#[derive(PartialEq, Debug)]
2424
pub enum List {
25-
Cons(i32, List),
25+
// 用 Box 包装 List,将递归类型转为固定大小的指针
26+
Cons(i32, Box<List>),
2627
Nil,
2728
}
2829

@@ -35,11 +36,13 @@ fn main() {
3536
}
3637

3738
pub fn create_empty_list() -> List {
38-
todo!()
39+
// 空列表直接返回 Nil 变体
40+
List::Nil
3941
}
4042

4143
pub fn create_non_empty_list() -> List {
42-
todo!()
44+
// 非空列表:嵌套 Cons 结构,最后用 Box::new(Nil) 终止递归
45+
List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))))
4346
}
4447

4548
#[cfg(test)]

0 commit comments

Comments
 (0)