Rust does not have try-catch blocks, instead it handles error management through Option and Result types.
Option blocks<T> are used for error management when the result can either be Some<T> or None(null). An example of this is showcased to the left.
In this code, we are trying to find a number within an array of integers. If we get a target number, then we return Some(index), otherwise, we return None.
Result blocks<T,E> are an enum that can either be T, or E(generic types). Using these types, you can create error mangement. An example is showcased to the left.
In the example, I create to error messages, when we are dividing by zero or by a negative number. If either of those two is the case, then the function will return an error message. Otherwise, it will return the division of the two numbers.
Rust allows a shorthand for propagating errors with the ? operator. If an expression returns a result or Some, using ? will automatically return the error if there is one, or the value if it's Ok or Some. An example is showcased to the left.
Here, we read the file to a string using the ? operator. If the file does not exist, or there is an error reading the file, then it will print out an error message. Otherwise, it returns the content of the file as a string.
Rust has explicit allocation, but does not have explicit deallocation. As I have mentioned in previous projects, Rust has unqiue references, borrowing, and onwership rules. When an object falls out of scope, rust automatically removes it. Comments are included in the entire file to showcase each case.
An example is showcased to the left. In this example, when we assing b to a, ownership of "data" goes from a to b, and so a is destroyed(freed). This causes an error if I try to print a again. If we do not want a to be destroyed, we can set b to be a copy of a, using a.copy(). In C, there is shared access, and so we can have both a and b point to the same place, and when one is freed, the other is as well.
An example of reading and writing to text files is included in the task2_rust file, where we read in a file from the command line and print out the 20 most common words. To do this, I used the standard io library.
I also implemented it interactively, where the user will input the text file as the program runs.
Rust does support binary files.
Rust does not support the opening of URL's within the standard libraary, although you can import libraries(crates) that add this functionality.
The example of when I used the reading of the file in the wordcounter file is showcased to the left.
As Rust does not implement a garbage collector in the traditional sense(instead using ownership, borrowing, and scope), I implemented the experiment in Java.
The code is showcased to the left. Basically, it allocates 50 MB per iteration, and if a specific iteration takes a significantly more amount of time than average, then we flag it as a possible garbage collection.