Books

Friday, January 03, 2020

Learning Rust - Day 1

So I decided to learn Rust. I have had it in mind for a while, but decided to start now. I see it as my contribution to the whole new year, new goals, new resolution brouhaha currently ravaging everywhere.

And since I am temporarily off twitter*, my go to place for shouting into the void, I am choosing to blog my experience here on my blog (like it’s 2006!). So basically I would be going through The Book as much as time allows me per week, and I would be journaling the good, the bad, and the utterly ugly things I find on the way here!

The plan is that, after I become proficient in rust, I can return to these posts and cringe at my ignorance!

So let us get started.



I just finished the first and second chapter of The book, and here are some of my thoughts.

Getting started is a breeze. The tooling feels matured, and there seems to be ample documentation. I started off with using Microsoft Code. But at some point, I switched to Intellij IDEA and installed the Rust plugin. Also I find the beginners section of the Rust channel on Discord to be quite approachable and helpful.

I am not yet sure how I feel about having to append every line with ";" (I remember reading somewhere that this is only necessary for statements, and with expressions, it is optional. I am yet to explore this assertion). In general, I like the idea of making statement distinguishable from expressions, but the amount of time, I had to be reminded about “;” in the short period I interacted with the language is a little bit annoying. But I have no say here, I have to get used to it!

I had to come up with the following code in chapter 2

use std::io;
use rand::Rng;
use std::cmp::Ordering;

fn main() {
    println!("Guess the number!");
    let secret_number  = rand::thread_rng().gen_range(1, 5);

    println!("Input your guess: ");

    loop {
        let mut guess = String::new();
        io::stdin().read_line(&mut guess).expect("Failed to read line");
        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => {
                println!("{} is not a number!", guess);
                continue;
            }
        };

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too low"),
            Ordering::Greater => println!("Too high"),
            Ordering::Equal => {
                println!("You got it");
                break;
            }
        }
    }

}

And I have some questions still.

Not sure why I had to have use rand::Rng even though I do not directly use it in the code. I got to learn this has to do with Traits. I chucked this up as something that would soon make sense when I understand Traits. It sort of feels like implicits in Scala, and type class instances in Haskell though, but too early to be definite about this.

I also found it confusing that I could use rand directly in the code without first doing use rand. My not so rigorous justification for this, is that having use a::b will also make a implicitly available. I am almost certain this is wrong. So I am looking forward to the illumination as I get to know the language proper.

In general I have found the whole module concept in Rust a little bit...slippery. At this point I am not even sure I know how things fit together. Maybe when I get to chapter 7, which covers packages and modules I would be enlightened.

There are some other interesting tips, knowledge I picked up in this session, which I share below in a QnA format:

Q. What does :: mean in String::new() in Rust?
     A. This is for accessing non instance methods/properties. Think static methods in Java

Q. How do I update dependencies in Rust?
     A. You can run `cargo update`

Q. What is shadowing in Rust?
     A. A mechanism that allows the redefinition of a variable. Quoting from the rust book: It allows us to shadow the previous value of guess with a new one. This feature is often used in situations in which you want to convert a value from one type to another type. Shadowing lets us reuse the guess variable name rather than forcing us to create two unique variables.

Q. How do I create an infinite while loop in rust?
     A. It turns out rust has a key word for that. So, you do not need to mess around with while loops and having to ensure the condition of the while loop is not meant. In rust you just do loop { stuff you want to run in a loop.}. You can use the usual suspects: break and continue.

Q. How do I do string formatting in rust?
     A. Check Formatting - Rust By Example

Q. Does rust have something similar to ??? like in Scala?
    A. Yes. The macros unimplemented!(), is exactly for that!

So that is it for today. Catch you the next time I find some free space to continue with the rust book.

*I am technically still on twitter as @dadepo, I just disabled my account. Which I enable for a day or two regularly to prevent total deletion!

No comments:

Post a Comment