Learn to Code via Tutorials on Repl.it!

← Back to all posts
The Little Rustacean, Pt 1. Some Old Friends
doineednumbers (26)

Hello, do you want to learn Rust? Do you like the style of The Little Schemer? Well, read this series of posts, and you might learn a thing or two.
Q: Write a program that prints Welcome To Rust,
A:

fn main() {
    println!("Welcome To Rust");
}

Q: What does this code do?

fn double(str: String) {
    println!(str);
    println!(str);
}
fn main() {
    double("Welcome to Rust, I hope you enjoy your stay");
}

A: This defines a function named double, which prints a string twice. It then defines a function named main, which calls double with the input Welcome to Rust, I hope you enjoy your stay. Then, the program calls the function main
Q: Is this all you need?
A: Not quite, some memory and math would be nice, and if would be good as well.
Q: How do we do math in Rust?
A: Do it like you learned in school. 1 + 1 is 2, of course, and 2 * 6 / 3 makes 4.
Q: What is memory?
A: What the computer remembers.
Q: How do you use memory?
A: Like this:

fn main() {
    let str = "Hi there";
    println!(str);
}

Q: Can you change a string?
A: Sure, but it needs to be mutable.

fn main() {
    let mut str = "Hi!";
    println!(str);
    str = "I am new";
    println!(str);
}

Q: Ok, cool! Is that everything you need?
A: No. One more thing. You need conditional branching
Q: What's that?
A: The ability to do different things depending on what happens.
Q: How do you do that in Rust?
A: Like this:

if (5 + 3 == 8) {
    println!("Correct!")
}
else if (5 + 4 == 9) {
    println!("You won't get here, but if you do, this will only happen if 5 + 9 is 9");
}
else {
    println!("You definitly won't get here, but this would happen if the first two are false");
}

Q: Got it?
A: Yup.
Q: Ok, is that everything you need?
A: Yes.
Q: Would now be a good snack break?
A: Definitly
Q: What does this do?

fn main() {
    for x in 0..10 {
        println!("{},", x);
    }
}

A: It loops through an iterator that has 0-10 in it, and prints the number that the loop is on.
Q: What does this do?

fn main() {
    for x in ["Hi there", "Why?"] {
        println!("{}", x);
    }
}

A: It loops through an array and prints each element.
Q: Can you use while loops in Rust?
A: Yes, like this:

while (true) {
    print("Hi")
}

Q: Are you ready?
A: To stumble through your first real program.
Q: Should you learn more first?
A: Yes.

Comments
hotnewtop
doineednumbers (26)

Good, I wasn't stupid and used correct type syntax.