Skip to content

Instantly share code, notes, and snippets.

@Shaun289
Created October 29, 2021 01:33
Show Gist options
  • Save Shaun289/9b3dece111068b98927ccf371fcf3879 to your computer and use it in GitHub Desktop.
Save Shaun289/9b3dece111068b98927ccf371fcf3879 to your computer and use it in GitHub Desktop.
Rust study : enum Linked List
/*
The rust by example ko https://hanbum.gitbooks.io/rustbyexample/content/custom_types/enum/testcase_linked_list.html
compiled on https://play.rust-lang.org/
result:
running 1 test
test tests::test_list ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
*/
use List::*;
enum List {
// Cons: 튜플 구조체로 보관하는 것은 요소와 다음 노드 포인터
Cons(u32, Box<List>),
// Nil: 노드로 linked list의 끝을 식별
Nil,
}
// 메소드는 enum에 접목될 수 있다.
impl List {
fn new() -> List {
Nil
}
fn prepend(self, elem: u32) -> List {
// 'Cons' 또한 List 타입을 갖는다.
Cons(elem, Box::new(self))
}
fn len(&self) -> u32 {
/* 'self'가 일치해야 되는 이유는 이 메소드의 행위가
self의 변수형에 달려있기 때문이다.
self는 *List 타입이고 *self는 List 타입
정확한 타입 T가 참조 &T 보다 match에서 선호된다.
*/
match *self {
Cons(_, ref tail) => 1 + tail.len(),
Nil => 0
}
}
// 반환하는 것은 list를 string으로 표현한 것(heap 할당된)
fn stringify(&self) -> String {
match *self {
Cons(head, ref tail) => {
// format!은 print!와 유사하지만 힙에 할당된 string을 반환한다.
format!("{}, {}", head, tail.stringify())
},
Nil => {
format!("Nil")
}
}
}
}
#[cfg(test)]
mod tests
{
use super::*;
#[test]
fn test_list()
{
let mut list = List::new();
list = list.prepend(1);
assert_eq!(list.len(), 1);
assert_eq!("1, Nil".to_owned().eq(&list.stringify()), true);
list = list.prepend(2);
assert_eq!(list.len(), 2);
assert_eq!("2, 1, Nil".to_owned().eq(&list.stringify()), true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment