How it works...
Rust and many other programming languages use the Result type to communicate multiple function outcomes at once. This way, the function can return just as it was designed without (unexpected) jumps such as the exception mechanism.
In step 3 of this recipe, we show one way of communicating errors that is common in other languages (for example, Java)—however, as we can see in the test (step 6), the outcome for an empty string is unexpected (0 instead of -1). In step 3, we define a better return type, but is it enough? No, it isn't. In step 4, we implement the best version of the function where each Result type is easy to interpret and clearly defined.
One even greater example of how to use Result can be found in the standard ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access