Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Possible to implement From T> and From on the same type, or at least emulate it?
Possible to implement From T> and From on the same type, or at least emulate it?
ā Rust š 2025-09-04 š¤ surdeus šļø 3Let'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
š·ļø Rust_feed