QUIK TIP
» EXPECT AND UNWRAP
QUIK TIP
» THE VECTOR DATA TYPE
A Rust trait is a collection of methods defined for an unknown type: Self. Put simply, a trait describes an abstract interface that can be implemented by other data types. So traits define a behaviour. See https://doc. rust-lang.org/ std/io/trait. Read.html.
Both expect() and unwrap() are used with the Result and Option data types and allow you to deal with error and unexpected conditions. Put simply, they allow you to get the value from a Result or Option variable, if it exists, or deal with the error condition the way you want to. The generic format of a Result value is <&a_value, Error> , which means that we can either get Ok(&a_value) if it exists or get an Err(Error) value whereas the generic format of an Option value is Option<&a_value> , which means that we either get a valid value Some(&a_value) or None . Bear in mind that Some is a data constructor. You can learn more about Option and Some by visiting https://doc.rust-lang.org/std/option/enum.Option.html.
If you’re keen to experiment with file I/O in Rust, you can try implementing the cat utility. You could also write a utility that reads plain text files and replaces a predefined string with another one, and then writes the output to a different file.
The Vector data type is very popular in Rust, so it deserves some extra attention. First of all, a Vector is like an array. As is the case with arrays, index values start from 0. The main advantage of vectors over arrays is that vectors can be resized, provided that they’re declared as mutable. You can put or remove vector elements using pop() and push(), respectively. Additionally, apart from the size, which is the number of elements stored, a vector has a capacity, which is the amount of memory reserved for the vector. Finally, a vector represents a pointer to the data.
OUR EXPERT
Having a Result value returned by a function named get_result() , we can extract its data as follows:
You can select the part of a Vector that you want to access using an index range, as occurs in read.rs. So, for a vector named a_vector, you can select its first two elements by writing &a_vector[0..2] . You can iterate over the elements of a vector in various ways. One such way is by using a for loop using the index of the element you want to access. Another approach is to use an iterator, which for a_vector is called as a_vector.iter() , to obtain all vector elements one by one. Remember that if you use an index value greater than or equal to the length of the vector, your code is going to crash.
Mihalis Tsoukalos is a systems engineer and a technical writer. You can reach him at @mactsouk.