Possible to implement From T> and From on the same type, or at least emulate it?

āš“ Rust    šŸ“… 2025-09-04    šŸ‘¤ surdeus    šŸ‘ļø 3      

surdeus

Let's say I have the following enum.

enum MaybeFnOrVal<T> {
    Val(T),
    Fn(Box<Fn() -> T>),
}

I’d like to be able to impl From for both of these cases.

impl<T> From<T> for MaybeFnOrVal<T> {
    fn from(v: T) -> Self {
        Self::Val(v)
    }
}

impl<F, T> From<F> for MaybeFnOrVal<T>
where
    F: Fn() -> T,
{
    fn from(f: F) -> Self {
        Self::Fn(Box::new(f))
    }
}

let x: MaybeFnOrVal<i32> = MaybeFnOrVal::from(5);
let y: MaybeFnOrVal<i32> = MaybeFnOrVal::from(|| 5);

assert!(matches!(x, MaybeFnOrVal::Val(_));
assert!(matches!(y, MaybeFnOrVal::Fn(_));

I understand these conflict with each other because T might impl Fn() → Self, but that seems like a nonsensical case.

2 posts - 2 participants

Read full topic

šŸ·ļø Rust_feed