Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::fmt::{self, Formatter, Display};
- #[derive(Debug)]
- enum Error {
- InvalidId,
- Conversion,
- }
- impl Display for Error {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- match self {
- Error::InvalidId => write!(f, "Missing book ID"),
- Error::Conversion => write!(f, "Could not convert book ID into a number"),
- }
- }
- }
- fn book_id(id: Option<&str>) -> Result<String, Error> {
- id
- .ok_or(Error::InvalidId)
- .and_then(|v| v.parse::<i16>().map_err(|_| Error::Conversion))
- .map(|n| format!("Your book ID is {}", n))
- }
- fn response(inp: Result<String, Error>) -> String {
- inp.unwrap_or_else(|err| format!("{}", err))
- }
- fn main() {
- println!("{}", response(book_id(Some("10"))));
- println!("{}", response(book_id(None)));
- println!("{}", response(book_id(Some("abc"))));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement