Hello Rust – Learning a programming language

on
Nov 28, 2018
in

In my opinion, the best thing about being a developer, is learning a new programming language. Learning something new brings you out of your comfort zone, you make mistakes and as you learn the new syntax and concepts you start to get an appreciation of the language. Learning a new language is certainly a challenge and challenges are fun!. Lets take a quick look at Hello World with Rust!

Hello Rust

In my previous blog about Rust, we looked at Learning Cargo – The build tool for Rust. Cargo manages Rust codebases by introducing the Rust module system called Crates. There are ‘binary’ crates for applications and ‘library’ crates for well, libraries! Lets create a Hello World ‘binary’ crate:

$ pwd
~/projects

# create a new project
$ cargo new hello-rust

cd hello-rust
$ cargo run
Hello, world!

Lets edit ‘src/main.rs’ and change it to:

fn main() {
    let xs = [1, 2, 3, 4, 5];
    for x in &xs {
        print!("{} ", x);
    }
    println!("Hello, world!");
}

Outputs:

$ cargo run
1 2 3 4 5 Hello, world!

SegFaults?

In the blog Looking back at C and C++ we looked at how easy it is to illegally access memory, causing an application crash. As rust is a modern Systems Programming Language, I wonder if that is also possible with Rust.

fn main() {
    let mut xs = [1, 2, 3, 4, 5];

    // surprise!
    xs[10] = 10;
    let x = xs[100];
    println!("{}", x);
}

Outputs:

$ cargo run
   Compiling hello-rust v0.1.0 (/Users/dennis/projects/hello-rust)
error: index out of bounds: the len is 5 but the index is 10
 --> src/main.rs:3:5
  |
3 |     xs[10] = 10;
  |     ^^^^^^
  |
  = note: #[deny(const_err)] on by default

error: index out of bounds: the len is 5 but the index is 100
 --> src/main.rs:4:13
  |
4 |     let x = xs[100];
  |             ^^^^^^^

error: aborting due to 2 previous errors

error: Could not compile `hello-rust`.

Perfect! The example does not compile and gives feedback on the problem and how to fix it.

Dependencies

Lets add a dependency to create random numbers. Edit the Cargo.toml file and add the rand crate (library). I like the terminology!

[package]
name = "hello-rust"
version = "0.1.0"
authors = ["Dennis Vriend <dnvriendvriend@binx.io>"]
edition = "2018"

[dependencies]
rand = "0.3.14"

To use the crate, we have to register it with Rust. We use the keywords extern crate. We then bring ‘io::Rng’ in scope with the use keyword. We then loop 10 times and print a random generated number.

extern crate rand;

use rand::Rng;

fn main() {
    for x in 1..11 {
        let random_number = rand::thread_rng()
            .gen_range(1, 101);
        println!("{} -> {}", x, random_number)
    }
}

Outputs:

$ cargo run
   Compiling hello-rust v0.1.0 (/Users/dennis/projects/hello-rust)
    Finished dev [unoptimized + debuginfo] target(s) in 0.55s
     Running `target/debug/hello-rust`
1 -> 89
2 -> 2
3 -> 75
4 -> 84
5 -> 3
6 -> 56
7 -> 82
8 -> 66
9 -> 17
10 -> 76

Conclusion

In this blog we have created a hello world example. Then we tried to crash the application by illegally accessing memory ie. segfault, but the Rust compiler prevents that. We then imported an external dependency ‘rand’ that provides random number generators. We generated 10 random numbers and printed the result to the console. We used Cargo, the Rust build tool to build all the examples.
I’m still making a lot of beginner mistakes, but I’ll stick with it, having fun in the meantime!

Share this article: Tweet this post / Post on LinkedIn