I'm trying to create a new type, which will be i16
, but print and parse differently:
use std::fmt;
use std::str::FromStr;
pub type Data = i16;
impl fmt::Display for Data {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "0x{:04X}", self)
}
}
impl FromStr for Data {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let hex: String = s.chars().skip(2).collect();
let d = Data::from_str_radix(&hex, 16)
.expect(&format!("Can't parse hex '{}' in '{}'", hex, s));
Ok(d)
}
}
#[test]
pub fn prints_itself() {
let data : Data = 42;
assert_eq!("0x003A", format!("{}", data));
}
#[test]
pub fn parses_itself() {
let data : Data = 42;
assert_eq!(data, "0x003A".parse());
}
It doesn't compile and I think I understand why. It seems I should declare my type Data
somehow differently. How?