in Review, Uncategorized

Introduction to Rust-lang

Rust is a compiled, statically-typed, non-garbaged collected systems programming language. An initiative by Mozilla, it has attracted a lot of traction lately because of its blazing fast speed and the high level abstraction(as the rust-lang page says “Zero cost abstractions”).

Read Time ~10 mins.

Lets see a sample code from rust –

fn main() {
    // A simple integer calculator:
    // `+` or `-` means add or subtract by 1
    // `*` or `/` means multiply or divide by 2

    let program = "+ + * - /";
    let mut accumulator = 0;

    for token in program.chars() {
        match token {
            '+' => accumulator += 1,
            '-' => accumulator -= 1,
            '*' => accumulator *= 2,
            '/' => accumulator /= 2,
            _ => { /* ignore everything else */ }
        }
    }
    println!("The program \"{}\" calculates the value {}",
              program, accumulator);
}

Some clear similarities with C/C++ flow of program starts from the main function. We define functions with fn keyword and commenting is again similar to C.

let lets us define variables(or rather variable-bindings). Now why don’t we see a variable type in the whole expression, this is because rust has type inference included. What this means is you don’t have to mention types as often, while you can still specify types by adding type annotations.

let rand_int:i32 = 10

Mutability

What does the mut keyword do here? Variable bindings in rust are immutable by default, that means if you try to run the code below rust compiler will throw an error.

fn main() {
    let str = "+ + * - /";
    str = "new string"; // Error: re-assignment of immutable variable
}

To make str mutable we’ll have to add the mut keyword in front of it.

let mut str = "+ + * - /";

 

The for in construct iterate through an iterator pretty familiar stuff. There are a couple of more looping constructs like while cond and loop(loops infinitely).

Pattern Matching

Next we see the match expression, match is the pattern-matching implementation in rust. Functional programmers should feel right at home here. If you are not familiar with pattern matching yet, you can think of match as switch statement on steroids.

Macros

println as its name suggest prints the formatted string {} are used to substitute parameters in string.But what is there ! in front of it. Well this is because println is not a function in rust it is a macro, again a similarity to C.

Ownership

Ownership would be the most eccentric feature of rust as a language.
Variable bindings have a property in Rust: they have ownership of what they are bound to. This means that when a binding goes out of scope, Rust will free the bound resources.

fn take(v: Vec<i32>) {
    println!("First value {}", v[0]);
}

let v = vec![1, 2, 3];

take(v);

println!("v[0] is: {}", v[0]); //ERROR: error: use of moved value: `v`

To make the above program work we would have to return the ownership from take() to the outer scope by returning v.

fn take(v: Vec<i32>) {
    println!("First value {}", v[0]);
}

let v = vec![1, 2, 3];

let v = take(v); // Variable shadowing

println!("v[0] is: {}", v[0]); //Prints -> "v[0] is: 1"

You might be thinking this could get ugly very fast, well to make this easier rust also has a concept of borrowing.

Well that’s it for this post. Using python as the primary language to develop, rust has been a great change its amazingly fast and the compiler is awesome at finding out issues which would have been otherwise caught at runtime.

Bonus: if you are a vim user like me plugins have already been developed checkout rust.vim

Let me know your thoughts about rust.

Write a Comment

Comment

  1. I was just looking at your Introduction to Rust-lang | Code Ignite site and see that your site has the potential to get a lot of visitors. I just want to tell you, In case you don’t already know… There is a website service which already has more than 16 million users, and most of the users are looking for websites like yours. By getting your site on this network you have a chance to get your site more popular than you can imagine. It is free to sign up and you can read more about it here: http://thrivemarket.ru/ja – Now, let me ask you… Do you need your website to be successful to maintain your way of life? Do you need targeted traffic who are interested in the services and products you offer? Are looking for exposure, to increase sales, and to quickly develop awareness for your website? If your answer is YES, you can achieve these things only if you get your site on the network I am talking about. This traffic network advertises you to thousands, while also giving you a chance to test the network before paying anything at all. All the popular sites are using this network to boost their readership and ad revenue! Why aren’t you? And what is better than traffic? It’s recurring traffic! That’s how running a successful website works… Here’s to your success! Read more here: http://s.t0m-s.be/5q

  2. This is a memo to the admin. I came to your Introduction to Rust-lang | Code Ignite page by searching on Google but it was difficult to find as you were not on the front page of search results. I know you could have more visitors to your site. I have found a site which offers to dramatically increase your rankings and traffic to your website: http://korturl.no/1tg1z} I managed to get close to 500 visitors/day using their service, you could also get a lot more targeted traffic from search engines than you have now. Their service brought significantly more visitors to my website. I hope this helps!