Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

By the mean of polymorphism we can make error handling quite easy to use. The key features we will use to achieve this, are:

First, we import the Error trait:

Then we implement a function that reads float numbers from strings, and use two functions that return Result objects that both use different error objects. These both error types (std::collections::TryReserveError and std::FromStr::Err) implement the Error trait. Instead of naming them explictly inside the returned Result object of the structure, we use the Error trait inside a Box. The error objects will thus be moved to the heap inside a Box. For both functions, we use the ? operator to retrieve the value or return with the error:

The following intermediate function will blindly pass any error object that is returned by the read_floats() function:

When calling the do_stuff() function, we apply a match to take actions depending on the success or not:

An error occured: invalid float literal
()