Last updated
Last updated
In Rust, the Result<T, E>
struct is used to abstract both a successful response (if it exists) and an error (if it occurs). Let's better understand through an example.
Consider that you have a function divide(num1, num2)
, which executes the division between two numbers. As you already know, dividing by 0 is undefined, and generates an error in Rust. You can use Result
to return a controlled error.
Let's inspect the divide
function:
Declaration of the function. Two unsigned numbers of 32-bit length are passed as parameters. The return type is Result<u32, String>
: the first type (u32
) is for the successful response, and the second type (String
) is for the error response.
If dividing by 0, you return an error String.
If not, you return the result of the division (u32
).
The Result<T, E>
is really an enum that can take two values: Ok(T)
(success) and Err(E)
(error).
In the previous code, when you return Err(String)
, the success part is automatically empty. At the same time, when you return Ok(u32)
, the error part is empty.
Now, let's see how you can interact with this result.
You invoke the function and store the Result<T,E>
enum in a variable.
If the result is ok (i.e. the happy path has been returned), you can take its value by using the result.unwrap()
method.
If the error has been returned, you can return the error string by using the result.err().unwrap()
method.
The output of the program for divide(6,2)
(happy path) is:
The output of the program for divide(6,0)
(error) is:
Checking with an if
condition whether the result contains an error is a valid approach. However, Rust includes a shortcut to improve this.
In the previous example, consider that you want to invoke the divide
function from another function that performs other computations.
Now, the Rust program adds 5
to the result of the division, checking that the division is correct first. Although this approach is correct, Rust provides a ?
symbol that simplifies the logic:
The ?
symbol after a Result
enum does two things:
If successful, it unwraps the result (in this case, a u32
number), and stores it in a variable let division_result = divide(6, 0)?;
If an error occurs, it returns the error directly. In this example, the error type of the divide
and the computations
function is the same (a String
).
The Result
enum is used in Substreams to return the data (or the errors) of a module. For example, if you take the map_filter_transactions
module from the :
This module returns a Result<Transactions, Vec<substreams::errors::Error>>
enum. If successful, it returns the transactions filtered; in the case of an error, it returns the substreams::errors::Error
error, which is a Substreams wrapper for a generic .