Created
June 2, 2020 05:10
-
-
Save nikkon-dev/b0bea314d57f57eaa6b1d79f64fcba31 to your computer and use it in GitHub Desktop.
Rust macro to create lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_export] | |
macro_rules! list { | |
($val: expr => $($tail: expr)=>+) => { | |
{ | |
let mut node = ListNode::new($val); | |
node.next = Some(Box::new($crate::list!($($tail)=>+))); | |
node | |
} | |
}; | |
($val: expr) => { | |
ListNode::new($val) | |
}; | |
() => { | |
ListNode::default() | |
}; | |
} | |
#[derive(Default, Debug)] | |
struct ListNode<T> { | |
pub(crate) next: Option<Box<ListNode<T>>>, | |
pub val: T, | |
} | |
impl<T> ListNode<T> { | |
fn new(value: T) -> Self { | |
ListNode { | |
next: None, | |
val: value, | |
} | |
} | |
} | |
#[test] | |
pub fn empty() { | |
let list: ListNode<i32> = list![]; | |
assert_eq!(list.val, 0); | |
} | |
#[test] | |
pub fn single() { | |
let list = list![1]; | |
assert_eq!(list.val, 1); | |
assert_eq!(list.next.is_none(), true); | |
} | |
#[test] | |
pub fn many(){ | |
let list = list![1 => 2]; | |
assert_eq!(list.val, 1); | |
assert_eq!(list.next.is_some(), true); | |
match(list.next){ | |
Some(ref next) => { | |
assert_eq!(next.val, 2); | |
assert_eq!(next.next.is_none(), true); | |
}, | |
None => { | |
assert!(false); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment