基础用法

  1. enum TimeUnit {
  2. Seconds,
  3. Minutes,
  4. Hours,
  5. Days,
  6. Months,
  7. Years,
  8. }

高级用法

  1. enum RoughTime {
  2. InThePast(TimeUnit, u32),
  3. JustNow,
  4. InTheFuture(TimeUnit, u32),
  5. }

带方法的enum

  1. impl TimeUnit {
  2. fn plural(self) -> &'static str {
  3. match self {
  4. TimeUnit::Seconds => "seconds",
  5. TimeUnit::Years => "years",
  6. TimeUnit::Days => "days",
  7. TimeUnit::Hours => "hours",
  8. TimeUnit::Minutes => "minutes",
  9. TimeUnit::Months => "months",
  10. }
  11. }
  12. }

变态用法

  1. #[derive(Debug)]
  2. struct TreeNode<T> {
  3. element: T,
  4. left: BinaryTree<T>,
  5. right: BinaryTree<T>,
  6. }
  7. #[derive(Debug)]
  8. enum BinaryTree<T> {
  9. Empty,
  10. NonEmpty(Box<TreeNode<T>>),
  11. }
  12. impl<T:Ord> BinaryTree<T> {
  13. fn add(&mut self, value: T) {
  14. match self {
  15. &mut BinaryTree::Empty => {
  16. *self = BinaryTree::NonEmpty(Box::new(TreeNode {
  17. element: value,
  18. left: BinaryTree::Empty,
  19. right: BinaryTree::Empty,
  20. }))
  21. },
  22. &mut BinaryTree::NonEmpty(ref mut node) => {
  23. if value <= node.element {
  24. node.left.add(value);
  25. }else {
  26. node.right.add(value);
  27. }
  28. }
  29. }
  30. }
  31. }

Cow

  1. enum Cow<'a, B: ?Sized + 'a>
  2. where B: ToOwned
  3. {
  4. Borrowed(&'a B),
  5. Owned(<B as ToOwned>::Owned),
  6. }
  1. fn remove_space(input: &str) -> Cow<str> {
  2. if input.contains(' ') {
  3. let mut buf = String::with_capacity(input.len());
  4. for c in input.chars() {
  5. if c != ' ' {
  6. buf.push(c);
  7. }
  8. }
  9. // T: String
  10. // U: From<String>
  11. return buf.into();
  12. }
  13. return input.into();
  14. }
  1. enum StatusCode {
  2. NotFound,
  3. InternalError(u32),
  4. }
  5. fn describe_status(s: StatusCode) -> Cow<'static, str> {
  6. match s {
  7. StatusCode::NotFound => "resource not found".into(),
  8. StatusCode::InternalError(code) => format!("internal error, status code {}", code).into(),
  9. }
  10. }