pub trait ParseNum {
// Required method
fn parse_num<T: Num>(&self) -> Result<T, T::FromStrRadixErr>;
}
Required Methods§
Sourcefn parse_num<T: Num>(&self) -> Result<T, T::FromStrRadixErr>
fn parse_num<T: Num>(&self) -> Result<T, T::FromStrRadixErr>
Parse string to number
This trait is default implemented for str, so both str
and String
type can use this method
Unlike from_str_radix where user must provide a radix, this method support auto hex, dec, oct, bin detection
§Examples
use string_to_num::ParseNum;
assert_eq!("0".parse_num::<i32>().unwrap(), 0i32);
assert_eq!("10".parse_num::<f32>().unwrap(), 10f32);
assert_eq!("0x01".parse_num::<u16>().unwrap(), 1u16);
assert_eq!("0xFF".parse_num::<f64>().unwrap(), 255f64);
assert_eq!("0b1111".parse_num::<u8>().unwrap(), 0b1111u8);
assert_eq!("0o1463".parse_num::<u16>().unwrap(), 0o1463u16);
assert_eq!("0XfF".to_string().parse_num::<f64>().unwrap(), 255f64);
assert_eq!("0B1111".to_string().parse_num::<u8>().unwrap(), 0b1111u8);
assert_eq!("0O1463".to_string().parse_num::<u16>().unwrap(), 0o1463u16);
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.