-
Notifications
You must be signed in to change notification settings - Fork 154
Examples
Peter Glotfelty edited this page Aug 18, 2019
·
1 revision
Using EnumMessage
for quickly implementing Error
extern crate strum;
#[macro_use]
extern crate strum_macros;
use std::error::Error;
use std::fmt::*;
use strum::EnumMessage;
#[derive(Debug, EnumMessage)]
enum ServerError {
#[strum(message="A network error occured")]
#[strum(detailed_message="Try checking your connection.")]
NetworkError,
#[strum(message="User input error.")]
#[strum(detailed_message="There was an error parsing user input. Please try again.")]
InvalidUserInputError,
}
impl Display for ServerError {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}", self.get_message().unwrap())
}
}
impl Error for ServerError {
fn description(&self) -> &str {
self.get_detailed_message().unwrap()
}
}
Using EnumString
to tokenize a series of inputs:
extern crate strum;
#[macro_use]
extern crate strum_macros;
use std::str::FromStr;
#[derive(Eq, PartialEq, Debug, EnumString)]
enum Tokens {
#[strum(serialize="fn")]
Function,
#[strum(serialize="(")]
OpenParen,
#[strum(serialize=")")]
CloseParen,
#[strum(default="true")]
Ident(String)
}
fn main() {
let toks = ["fn", "hello_world", "(", ")"].iter()
.map(|tok| Tokens::from_str(tok).unwrap())
.collect::<Vec<_>>();
assert_eq!(toks, vec![Tokens::Function,
Tokens::Ident(String::from("hello_world")),
Tokens::OpenParen,
Tokens::CloseParen]);
}