Returning unimportant result


#1

I have a setter method which can theoretically fail (in multiple different ways, e.g. value too low, value too high), but it’s an edge case and in practice it’s unlikely to happen. I’d like library users to be able to check the result if they need/want to, but I don’t want to cause warnings or add boilerplate for users who don’t care.

  • If I return bool, I won’t be able to state reason for failure.
  • If I return Option<Error> it will be a weird reversal of success/failure.
  • if I return Result<(), Error> Rust will bug users to check for the result.

Is there something that nullifies #[must_use]? #[use_or_dont_use_I_dont_care]?


#2

you could return your own enum:

pub enum Foo {
    Ok,
    Err(ErrType)
}

#3

IMO, this is the wrong approach.

If the failure is due to programmer error (illegal argument), just panic. Otherwise, I really would just return a Result and let the library user handle it. If you want to be nicer to users, try to limit the places where the user has to handle these errors. If the failure is astronomically unlikely (e.g. counter overflow) in normal operation, just panic and document the it (and pray that aerospace programmers actually read the documentation…).

Anyway, is there some code we can look at?


#4

If the failure is something the user should notice if it happens, regardless of how likely / unlikely it is, just return a Result (or panic, but I’d prefer to avoid that).

If the failure is something the user is unlikely to care about (maybe writing something to a cache or log a statistic, etc), you could provide two versions of the function, like this:

checked_foo(args) -> Result<(), Error> {
    ... do the actual stuff ...
}
foo(args) {
    let _ = checked_foo(args);
}

#5

Second to the two functions. I love the pattern they use in Core in OCaml: there are

zip     : 'a list -> 'b list -> ('a, 'b) list option
zip_exn : 'a list -> 'b list -> ('a, 'b) list

and the zip_exn version would throw if the lengths are different.

Although let _ = or .unwrap() in Rust is not that much boilerplate imo.


#6

Thanks for your suggestions. If I implement my own Result-like enum, how can I give it most of Results usability? e.g. should I reimplement some/all methods of Result? Is there an equivalent of Carrier trait in stable?


#7

You could implement Into<Result<(), MyError>> so people could work with it as a Result if they really wanted to.