I have read:
Can enum variants have constant associated values? [duplicate]
How can I create enums with constant values in Rust?
My question takes these questions one step further by considering if we can have each enum variant is an 'unwrap' of Result
, returning the Ok
variant.
use std::str::FromStr;
#[derive(Debug, PartialEq, Hash)]
struct Address(String);
#[derive(Debug, PartialEq)]
enum Error {
ParsePointError
}
impl FromStr for Address { // conversion from `&str` to `Address` returns a `Result`
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.len() >= 20usize {
return Err(Error::ParsePointError)
}
Ok(Address(s.to_string()))
}
}
struct TokenAddress {}
impl TokenAddress {
pub const HERO: Address = Address::from_str("0x1234567").expect("ERROR: Unable to parse `HERO`");
}
The main API I wish to achieve is to be able to use TokenAddress::HERO
and this should return me a value of type Address
.
lazy_static!(...)
may help in this case where each value defined within the macro is initialized only once, however, it would be a hassle to define individual variable name within the macro itself, e.g.
lazy_static!{
pub static ref HERO_TOKEN_ADDRESS: Address = "...".expect("...");
}
I wish to use it in my main()
like so:
fn main() {
let hero_token_address = TokenAddress::HERO;
println!("{:?}", hero_token_address);
}