Thursday, January 23, 2014

Rust Introduction: Part 2

Getting User Input

Getting user input is something many programs will have to do. Most languages offer a very simple way to do it. Rust is no different. In order to read a line from a user you can simply use:

let input = io::stdin().read_line();

This will read in a line of text and store it in a variable as a string. Now, what if you want to read in an integer? In many languages you can simply call a method to parse a string and convert it to a integer. Rust has a solution just like this:

let number = int::from_str(string);

This works fine if the string can actually be converted into an integer. There is always a chance that the string will not be a number though. You may expect this int::from_str() to throw an exception in this case. You can then catch this exception and handle it accordingly. Rust does things a little differently though, leading to my next point.

There are no nullable pointers

Null reference exceptions are a very common occurrence in languages like C and its family. Newer languages have tried to help prevent this with increased protection on pointers. Rust takes this protection even further by not allowing null pointers at all.

Now there are times where a null value is very useful. For this reason, Rust does include a nullable type, similar to the "?" after a type in C# (e.g. int?). Rust's version of a nullable type is called an Option.

An Option is a type that either does or does not have a value. If it does not have a value, then it simply contains the word "None." If it does have a value, then it contains that value, which you can access with the word "Some." 

An option is defined like this:


pub enum Option<T>
{
    None,
    Some(T),
}


If we take this knowledge and combine it with our knowledge of a match (switch) statement, we can easily extract a value from this option, and handle it accordingly if it has no value.


match stringOption
{
    None => return "no value",
    Some(x) => return x
}



Creating Classes

There is no actual "class" type in Rust. Instead, you must use a struct and an impleme