NewToCode
NewToCode

Reputation: 211

How to return both bool & string Result from a function in Rust?

I have a function: f() -> Result<bool> but it internally has more information as a string which I wanna return in the result as well along with the bool.

So my desired function signature is something like: f() -> Result<bool, String>. How can I achieve this? A small example would be very helpful.

Upvotes: 0

Views: 890

Answers (1)

Jeremy Meadows
Jeremy Meadows

Reputation: 2561

The Result type returns one type for an error, and another for success. In the example you posted, f returns a bool if the function completed as intended, or a String if there was a failure along the way.

If you don't want to create a struct to contain both parts of the data (which is probably a bit nicer to read), you should wrap your output in a tuple. Your function signature would then look like f() -> Result<(bool, String), ()>, which returns both types if an Ok is returned, and no data (unit type) on an error. Your function would then return something like Ok((is_success, str_info)) or Err(()) (notice the double parens in both the tuple case and unit type case).

Upvotes: 2

Related Questions