基础用法
enum TimeUnit { Seconds, Minutes, Hours, Days, Months, Years,}
高级用法
enum RoughTime { InThePast(TimeUnit, u32), JustNow, InTheFuture(TimeUnit, u32),}
带方法的enum
impl TimeUnit { fn plural(self) -> &'static str { match self { TimeUnit::Seconds => "seconds", TimeUnit::Years => "years", TimeUnit::Days => "days", TimeUnit::Hours => "hours", TimeUnit::Minutes => "minutes", TimeUnit::Months => "months", } }}
变态用法
#[derive(Debug)]struct TreeNode<T> { element: T, left: BinaryTree<T>, right: BinaryTree<T>,}#[derive(Debug)]enum BinaryTree<T> { Empty, NonEmpty(Box<TreeNode<T>>),}impl<T:Ord> BinaryTree<T> { fn add(&mut self, value: T) { match self { &mut BinaryTree::Empty => { *self = BinaryTree::NonEmpty(Box::new(TreeNode { element: value, left: BinaryTree::Empty, right: BinaryTree::Empty, })) }, &mut BinaryTree::NonEmpty(ref mut node) => { if value <= node.element { node.left.add(value); }else { node.right.add(value); } } } }}
Cow
enum Cow<'a, B: ?Sized + 'a> where B: ToOwned{ Borrowed(&'a B), Owned(<B as ToOwned>::Owned),}
fn remove_space(input: &str) -> Cow<str> { if input.contains(' ') { let mut buf = String::with_capacity(input.len()); for c in input.chars() { if c != ' ' { buf.push(c); } } // T: String // U: From<String> return buf.into(); } return input.into();}
enum StatusCode { NotFound, InternalError(u32),}fn describe_status(s: StatusCode) -> Cow<'static, str> { match s { StatusCode::NotFound => "resource not found".into(), StatusCode::InternalError(code) => format!("internal error, status code {}", code).into(), }}