Comparing trait object and enum type

#[derive(Debug, Snafu)]
pub enum Myerror{
NameNotFound{name:String},
/*
and so on - other errors are  here 
*/
}

//this function searches for a name in database.
//if the 'name' is found, return Ok(). else return respective Err() .
//and if 'name' is invalid then return trait object like below.
fn search_name(name:&str) -> Result<String,Box<dyn Error + Send + Sync>> {
    /*
    ignore the code here.
    */
    //one of the error case is - if the 'name' is not matched return a trait object like below 
    return Err(Box::new(Myerror::NameNotFound{name:name.to_string()}));
}

//main code 
fn main() {
    if let Err(err) = search_name("user"){
        //Here if 'name' is not matched just wait don't exit from main().
        //But i have issue here while comparing trait object returned from search_name with "Myerror::NameNotFound"
        if  err == Myerror::NameNotFound{ //line no 24
            //
             println!("name {} not found",name);
           // wait()
        }
        //for every other error, exit from main
        else{
            return ;
        }
    }
    //ok case - continue
    else {
        //continue with execution
    }

}

At line no 24 I need to check whether error returned from search_name is NameNotFound or not. How to do this? .

If you need to match on an enum, then don't return a trait object in the first place. Using dyn Error is basically no good anywhere except in top-level application code, where the only reasonable error handling strategies are printing the error, silencing/swallowing it, or panicking/crashing with it.

At basically any other, inner level, if you have a precise error type, just use/return that concrete type instead. It's easy enough to go from a concrete type to a trait object if that's needed down the line, but the opposite direction is not nearly as easy/elegant/safe. (It loses type safety as it involves downcasting, and it unconditionally incurs an extra heap allocation due to the need for boxing.)

I cannot change the existing code , so i should keep returning trait object . is there anyway i can compare trait object and enum type?

Downcasting exists, but it really is a code smell in this scenario.

1 Like

is it possible to something like to_String() or any other method?

You shouldn't compare string representations of errors, they aren't intended to be machine-readable. If there's no way you can change the function, you shoud at most use the downcasting methods I linked to above.