Use cases for Try

As we move towards stabilising trait Try I'm trying :wink: to collate real-world, actually-implemented, examples.

Anyone who knows of such cases, or has a concrete use case they would like to see, please drop a reply in this thread. For general discussion of Try please start a new thread.

So far, the ones I know about fall into a few categories[1]:

Sidecars

Effectively drop-in replacements for the primary try-types with additional "magic" baked into the Try:

Ergonomics

Orphan rule avoidance

  • exit_safely: create custom return types for main which respond to ? and implement Termination with defined exit codes

Generic over Try

Background


  1. Disclaimer: many of these are my own publications ↩︎

Rayon has ParallelIterator::try_* methods too.

And in general, I think many downstream Iterator types would do well to customize try_fold for internal iteration, but they can't until Try is stable.

A very simple use-case which I've never actually checked to make sure it's possible to do, but I've been meaning to use Try to get ? support for a custom JavaScript engine Result type where Ok and Err values are the exact same (a JavaScript value) but Err variants have the top bit set in the discriminant to signify them being thrown as errors. The thing I'm solving here is of course that if I just use Result<Value, Value> then I end up with a 16 byte Result when I really only need 8.

Cross-posted to reddit: Reddit

I have a project where I use the Try trait. I use to get the ? support for a type.

It is a SDK for the PSP

I experimented with using it for the outcome of various kinds of rule evaluation, iterating over functions that return something roughly equivalent to a ControlFlow<bool> (notably the opposite behavior of Option<bool> for ? - it wants to exit early if the value is present, not absent), but with a more-ergonomic enum defined for the specific purpose - e.g.

enum Decide {
    /// End rule evaluation with an "allow" response.
    Allow,
    /// End rule evaluation with a "deny" response.
    Deny,
    /// Continue rule evaluation.
    Continue,
}

This worked well, but my project didn't have any other nightly dependencies, so I didn't end up actually using it.

One major use case that I want to see is cmp::Ordering. It has then and then_with build in, but it would be great if I could write something like:

fn cmp(&self, other: &Self) -> cmp::Ordering {
    // Return if Greater or Less, return `()` if equal
    Ord::cmp(&self.a, &other.a)?;
    // Reverse the next field, why not
    Ord::cmp(&other.b, &self.b)?;
    Ord::cmp(&self.c, &other.c)
}

The Azul GUI Framework would really need this for ergonomics, for two reasons: one, to convert from None to Update::DoNothing automatically on a failed downcast and two, to convert to FFI types (it uses a repr(C) for every OptionFoo in the C ABI).

Here is a callback from a file manager (current API):

struct CopyRef {
    app: RefAny,       // handle to the whole app's state
    drive_id: String,  // which drive to copy
}

// Opens the folder picker and returns immediately with DoNothing
// to not block UI thread. Window stays responsive while the 
// dialog is up
extern "C" 
fn button_clicked(mut data: RefAny, _: CallbackInfo) -> Update {
    let Some(copy) = data.downcast_ref::<CopyRef>() else {
        return Update::DoNothing;
    };
    let _ = FileDialog::open_directory(
        "Copy everything to…".into(),             // title
        OptionString::None,                       // default folder
        RefAny::new(CopyRef {                     // handed back to us later
            app: copy.app.clone(),
            drive_id: copy.drive_id.clone(),
        }),
        on_copy_folder, // called when the user has picked a file
    );

    Update::DoNothing // no UI change yet, only opens dialog and returns
}

// Later: user did something with the file dialog: framework calls back
// on_copy_folder with the CopyRef from the above and the result 
// from the file picker
extern "C" 
fn on_copy_folder(mut data: RefAny, mut info: CallbackInfo, result: RefAny) -> Update {

    // our own context back
    let Some(copy) = data.downcast_ref::<CopyRef>() else {
        return Update::DoNothing;
    };
    let (mut app, drive_id) = (copy.app.clone(), copy.drive_id.clone());
    drop(copy);

    // the dialog's result (an FFI OptionFileOpenResult, so first into a core Option)
    let Some(picked) = FileOpenResult::downcast(result).into_option() else {
        return Update::DoNothing;
    };

    // the chosen folder (an FFI OptionFilePath): None means the user cancelled
    let Some(path) = picked.path.into_option() else {
        return Update::DoNothing;
    };
    let folder = PathBuf::from(path.inner.as_str());

    // the app's state
    let app_handle = app.clone();
    let Some(mut state) = app.downcast_mut::<DriveState>() else {
        return Update::DoNothing;
    };

    // now do the thing
    copy_everything(&mut info, &app_handle, &mut *state, &drive_id, folder);

    // UI should refresh now
    Update::RefreshDom
}

With the try trait (and please also FromResidual), I can implement:

  • impl Try for OptionFoo so that OptionFoo with repr(C) has the same semantics as Option<Foo> and ? works on it without .into_option()
  • impl FromResidual<Option<Infallible>> for Update so that I can auto-convert from a failed downcast to an Update::DoNothing return enum with ?:
extern "C" 
fn on_copy_folder(mut data: RefAny, mut info: CallbackInfo, result: RefAny) -> Update {

    let copy = data.downcast_ref::<CopyRef>()?;
    let (mut app, drive_id) = (copy.app.clone(), copy.drive_id.clone());
    drop(copy);

    let picked = FileOpenResult::downcast(result)?;
    let folder = PathBuf::from(picked.path?.inner.as_str());

    let app_handle = app.clone();
    let mut state = app.downcast_mut::<DriveState>()?;
    copy_everything(&mut info, &app_handle, &mut *state, &drive_id, folder);

    Update::RefreshDom
}

It's just a lot more readable: both the OptionFileResult can convert directly into an Update without any ".into_option() else { return Update::DoNothing }" and the failed downcast Option<T> can also convert directly.

I cannot use Option<T> in an "extern C" callback because Rusts native Option doesn't have a stable ABI layout. Yes, the file picker should offload the actual copying to a separate thread, etc. etc. - but this is just an example, this is simply how you'd do "async" continuation-style callbacks with a C FFI, which is where the Try trait is very very useful at saving lines of code.

Not implemented as depending on nightly features is a no-go for the applications, but planned for when Try is stable – and if helps, I can come up with a demo branch:

Wrapping C APIs (mainly for embedded RTOSes) that return i32 (or isize) with negative errors. This wouldn't need Try if there were niche-aware like u31 and neg31, so I could return Result<u31, Error> where struct Error(neg31);.

With Try, there could be struct ResultU31(u32) that supports all the usual Result things including ?, but keeps everything in a single register.

[edit, added:] A sketch of this is available at Compiler Explorer