Stream: t-compiler

Topic: MaybeResult

Daan de Graaf (Dec 24 2018 at 13:35, on Zulip):

As a new contributor to rustc, I got a bit confused about the MaybeResult trait. I have a variable where the only type bound is MaybeResult<...>, and I would like my function to return an Option<..> based on the value of the MaybeResult variable I have. I have not encountered this trait before so I am not sure how to work with it.

Is possible to turn a MaybeResult<T> into an Option<T>? Or would I be better off changing the function signature to return a MaybeResult<..> as well?

I am also kind of curious what the design rationale is behind the trait itself.

nagisa (Dec 24 2018 at 13:58, on Zulip):

You can find the rustdoc for MaybeResult here. From the implementors it has it appears that this is either just T or Result<T, E>.

nagisa (Dec 24 2018 at 13:59, on Zulip):

So yes, you should be able to convert a T: MaybeResult<...> to an Option fairly easily.

nagisa (Dec 24 2018 at 14:01, on Zulip):

There two ways to approach this, actually

nagisa (Dec 24 2018 at 14:01, on Zulip):

one is to simply add a method to the trait that does exactly the conversion you want.

nagisa (Dec 24 2018 at 14:02, on Zulip):

the other would be something along the lines of

nagisa (Dec 24 2018 at 14:04, on Zulip):
fn<V, T: MaybeResult<V> + Into<Option<V>>>>(...) { ... }
nagisa (Dec 24 2018 at 14:04, on Zulip):

changing Into into your trait in this case, because there is no such implementation like Result<T, E>: Into<Option<T>>.

Daan de Graaf (Dec 24 2018 at 14:09, on Zulip):

Thanks a lot @nagisa! I think I should be able to get both those options working, I'll try the second option for now just to not mess too much with the trait itself

nagisa (Dec 24 2018 at 14:10, on Zulip):

I think changing the trait itself is a better and cleaner option overall

Daan de Graaf (Dec 24 2018 at 14:16, on Zulip):

Yes that's true for sure, I just do not feel very confident in changing the trait without really knowing how it's normally used :sweat_smile:. For example, I have no idea how an implementation can pull a T from a MaybeResult<T> without a method like into_option() or unwrap available. Then again, maybe that should not stop me from experimenting

Daan de Graaf (Dec 24 2018 at 14:37, on Zulip):

I ended up just adding an ok() method to the trait, corresponding to the ok() on normal Result<T>. It is indeed a much cleaner solution, and I think it makes sense given that the trait is so closely related to Result. :smile:

Last update: Jan 19 2020 at 10:10UTC