I’ve wanted something like this several times - it seems like some points in this thread have veered towards a fallible casting operator; my favorite mentioned syntax so far was as?.
Specifically, here’s one incarnation of something I’ve encountered many times (it usually involves enums, especially &str -> Enum, but there are plenty of other variants (excuse the pun) exhibiting a fallible cast/conversion like operation):
#[repr(usize)]
#[derive(Debug)]
pub enum Normal {
North = 0,
South = 1,
West = 2,
East = 3,
Up = 4,
Down = 5,
}
impl Normal {
// I want to implement a trait so I and my clients
// don't have to memorize another random function name
pub fn from_idx(idx: usize) -> Option<Self> {
use self::Normal::*;
match idx {
0 => Some(North),
1 => Some(South),
2 => Some(West),
3 => Some(East),
4 => Some(Up),
5 => Some(Down),
_ => None,
}
}
}
fn main() -> Result<(), Error> {
let i = 3;
// i want to write this for the fallible cast/conversion
let n = i as? Normal;
// always safe
let i2 = n as usize;
assert_eq!(i, i2);
}
Yes, I can write a custom method, e.g. from_idx. But having a fallible cast syntax like above, just appears much more elegant, succinct, obvious, and universally memorable to me.