Skip to content

Allow checking whether try_from would succeed without consuming the value #47

@CasBex

Description

@CasBex

I have a use case where I want to check whether something is a variant of a subenum like below, but keep ownership of the value if it is not. Below code will not compile because the try_from moves a.

use subenum::subenum;
#[subenum(BB)]
#[derive(Debug)]
enum T {
    A,
    #[subenum(BB)]
    B,
}

fn main() {
    let a = T::A;
    if let Ok(b) = BB::try_from(a) {
        println!("It's a BB {:?}", b);
    } else {
        println!("It's not a BB {:?}", a);
    }
}

Could you add support for something like below?

use subenum::subenum;
#[subenum(BB)]
#[derive(Debug)]
enum T {
    A,
    #[subenum(BB)]
    B,
}

// automatically generate this
impl BB {
    fn isvariant(other: &T) -> bool {
        match other {
            T::B => true,
            _ => false,
        }
    }
}

fn main() {
    let a = T::A;
    if BB::isvariant(&a) {
        println!("It's a BB {:?}", BB::try_from(a).unwrap());
    } else {
        println!("It's not a BB {:?}", a);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions