0

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.

1
  • What's wrong with a tuple? Result<(bool, String), MyError> Commented Dec 10, 2022 at 16:18

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

But I also want to return a string error like: Err("Error: invalid input"). So the double parenthesis for Err won't work
@NewToCode In that case, you should use Result<(bool, String), String> and that allows a String to be returned with your Err enum as you've just written.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.