Learning Rust

Reading the news that Rust reached 1.0 Alpha I decided to take a deeper look at it.

Getting Rust

Installing Rust under arch is as easy

$ sudo pacman -S rust

The above will install the latest version from the community repo. If you want the latest and greatest version you could also try the nightly build.

The lazy people can try it online.

Hello World!

Here comes the obligatory "Hello World!" code in Rust

fn main() {
    println!("Hello World!");
}

Immutability

Beeing a C++ const-nazi I really liked that by default all variable bindings are immutable.

fn main() {
    let x = 1;
    x+=1;
    println!("{}", x);
}

The example above will give you a compile error:

mut.rs:4:5: 4:9 error: re-assignment of immutable variable `x`
mut.rs:4     x+=1;
             ^~~~
mut.rs:3:9: 3:10 note: prior assignment occurs here
mut.rs:3     let x = 1;
                 ^
error: aborting due to previous error

By using the "mut" keyword we mark the variable as mutable

fn main() {
    let mut x = 1;
    x+=1;
    println!("{}", x);
}

So the code will print "2"

Rust will also emit a warning when not using variables or an error when trying to use uninitialized variables.

blogroll

social