Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Match arms don't work with ()? in one arm and Ok(()) in the other #50136

Closed
ghost opened this issue Apr 21, 2018 · 2 comments
Closed

Match arms don't work with ()? in one arm and Ok(()) in the other #50136

ghost opened this issue Apr 21, 2018 · 2 comments

Comments

@ghost
Copy link

ghost commented Apr 21, 2018

My rustc version: 1.25.0.


Currently this doesn't compile:

use std::fmt::Display;
use std::fmt::Error;
use std::fmt::Formatter;

struct A { s: Option<String>, }

impl Display for A {

    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        match self.s {
            // This is either Ok(()) or Err(_)
            Some(ref s) => write!(f, "{}", s)?,
            // This is obviously Ok(())
            None => Ok(()),
        }
    }

}

Error message:

error[E0308]: match arms have incompatible types
  --> tests/src/main.rs:13:28
   |
13 |             Some(ref s) => write!(f, "{}", s)?,
   |                            ^^^^^^^^^^^^^^^^^^^
   |                            |
   |                            expected enum `std::result::Result`, found ()
   |                            match arm with an incompatible type
   |
   = note: expected type `std::result::Result<(), std::fmt::Error>`
              found type `()`

error: aborting due to previous error

error: Could not compile `tests`.

Work around:

impl Display for A {

    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        match self.s {
            Some(ref s) => write!(f, "{}", s)?,
            None => (),
        };
        Ok(())
    }

}

I think the work around looks... weird, where one arm returns Result<>, the other returns (). While the first code looks pretty clear: both arms return Result<>.


Perhaps #24157 is related, I'm not sure.

Thank you,

@jonas-schievink
Copy link
Contributor

write!(f, "{}", s)? doesn't evaluate to a Result, it evaluates to (), so the error is correct.

The ? operator creates code that's roughly equivalent to this:

match write!(f, "{}", s) {
    Ok(val) => val,
    Err(e) => return e.into(),
}

@ghost
Copy link
Author

ghost commented Apr 21, 2018

@jonas-schievink Thank you very much :-) I'm closing this issue.

@ghost ghost closed this as completed Apr 21, 2018
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant