Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. use std::fmt::{self, Formatter, Display};
  2.  
  3. #[derive(Debug)]
  4. enum Error {
  5. InvalidId,
  6. Conversion,
  7. }
  8.  
  9. impl Display for Error {
  10. fn fmt(&self, f: &mut Formatter) -> fmt::Result {
  11. match self {
  12. Error::InvalidId => write!(f, "Missing book ID"),
  13. Error::Conversion => write!(f, "Could not convert book ID into a number"),
  14. }
  15. }
  16. }
  17.  
  18. fn book_id(id: Option<&str>) -> Result<String, Error> {
  19. id
  20. .ok_or(Error::InvalidId)
  21. .and_then(|v| v.parse::<i16>().map_err(|_| Error::Conversion))
  22. .map(|n| format!("Your book ID is {}", n))
  23. }
  24.  
  25. fn response(inp: Result<String, Error>) -> String {
  26. inp.unwrap_or_else(|err| format!("{}", err))
  27. }
  28.  
  29. fn main() {
  30. println!("{}", response(book_id(Some("10"))));
  31. println!("{}", response(book_id(None)));
  32. println!("{}", response(book_id(Some("abc"))));
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement