Why doesn't Option<&String> implement Deref to Option<&str>?

I think that's what I want to ask...? And actually it's for Result, I want to do:

	let flag = match std::env::var("FLAG").as_ref() {
            Ok("1" | "true") => true,
            _ => false,
	};

but I get

error[E0308]: mismatched types                                                                                                                                                                                                                                                                                                                                                                                                              
  --> file.rs:54:16
   |
53 |         match std::env::var("FLAG").as_ref() {
   |               ------------------------------------- this expression has type `Result<&String, &VarError>`
54 |             Ok("1" | "true") => true,
   |                ^^^ expected `&String`, found `&str`
   |
   = note: expected reference `&String`
              found reference `&'static str`

and it seems like it would work if Result<&String, &E> implemented Deref to Result<&str, &E>?

Out of spite I wrote:

trait ResultAsAstr<E> {
    fn as_str(&self) -> Result<&str, &E>;
}

impl<E> ResultAsAstr<E> for Result<String, E> {
    fn as_str(&self) -> Result<&str, &E> {
        match self {
            Ok(s: &String) => Ok(s.as_str()),
            Err(e: &E) => Err(e),
        }
    }

}

rather than deconstructing the Result and then matching the &String in the Ok case.

Because Deref can only return a reference, but Option<&str> is not a reference.

Perhaps you are looking for this?

4 Likes

Beautiful, thank you.

Yeah, as_deref is one of those hidden gems that would deserve to be much better known.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.