Guest User

Untitled

a guest
Nov 17th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. #![allow(dead_code)]
  2.  
  3. macro_rules! fun {
  4. (
  5. $fname:ident $args:tt -> $ok_ty:ty => throws $err_ty:ty
  6. {
  7. $($fbody:tt)*
  8. }
  9. ) => (
  10. fn $fname $args -> ::std::result::Result< $ok_ty , $err_ty >
  11. {
  12. Ok({
  13. $($fbody)*
  14. })
  15. }
  16. );
  17. }
  18.  
  19. macro_rules! throw {
  20. (
  21. $expr:expr
  22. ) => (
  23. return Err($expr)
  24. );
  25. }
  26.  
  27. fun!{ foo(b: bool) -> i32 => throws String {
  28. if b {
  29. throw!("Got true".into())
  30. };
  31. 42
  32. }}
  33.  
  34. fun!{ bar(b: bool) -> () => throws String {
  35. foo(b)?;
  36. }}
  37.  
  38. #[test]
  39. fn foo_true ()
  40. {
  41. if let Err(s) = foo(true) {
  42. assert_eq!(s, "Got true");
  43. } else {
  44. unreachable!();
  45. }
  46. }
  47.  
  48. #[test]
  49. fn foo_false ()
  50. {
  51. if let Ok(x) = foo(false) {
  52. assert_eq!(x, 42_i32);
  53. } else {
  54. unreachable!();
  55. }
  56. }
Add Comment
Please, Sign In to add comment