Day 4: Rust Functions and loops

Day 4: Rust Functions and loops

Today I’m looking at functions and loops. They are an important part of any language and deserve a closer look. Rust handles both slightly differently from JavaScript and it’s pretty easy to confuse them sometimes. Let’s start with function.

Functions

In Rust, functions are declared using fn and names are written in snake_case like variables.

fn main() { println!("Hello World."); } fn say_something() { println!("Something"); }
Code language: JavaScript (javascript)

They are called the same as in Javascript,

say_something();

In Rust however, arguments must have types in the function definition.

fn say_something(value: i32, label: char, is_dead: bool) { println!("something {value}, {label}, {is_dead}"); }
Code language: JavaScript (javascript)

I finally found out why semi-colons can be omitted sometimes. It all has to do with statements and expressions. to quote the Rust book,

Statements are instructions that perform some action and do not return a value. Expressions evaluate to a resulting value. Let’s look at some examples.

https://doc.rust-lang.org/book/ch03-03-how-functions-work.html

I knew this intuitively already, but apparently, it’s a bigger deal in Rust.
Anyway, expressions return values, while statements do not. We can leave out the semicolon on expressions and they will return the value. This is used at the end of functions and scope blocks,

let x = { let y = 9; y * 9 }; //x = 81
Code language: JavaScript (javascript)

If you put the semicolon at the end then the expression becomes a statement and doesn’t return anything.
Also if a function returns a value then you need to define the type using ->

fn test() -> i32 { 1 + 1 }

This is weird.

Functions return the last expression implicitly but you can exit a function early using the return keyword. So if you are not feeling especially rusty this is valid:

fn test() -> i32 { return 1 + 1; }
Code language: JavaScript (javascript)

Conditionals

If statements work pretty much the same as in JS with one exception, you do not need the parentheses:

if condition { //do something }
Code language: JavaScript (javascript)

Same as else and else if.

There is something new though, in Rust if is an expression, therefore it can be used to assign a value to a variable. This is not a weird concept, it’s basically acting as a ternary in javascript
So in JS, we’d have

const test = isTrue ? 1 : 2
Code language: JavaScript (javascript)

and in rust we have

let test = if is_true { 1 } else { 2 }
Code language: JavaScript (javascript)

A bit more verbose but more readable.

We have to be careful though because both if and else outputs have to be the same type otherwise errors occur. Another perk of being strongly typed.

Looping

Rust like JavaScript has for and while loops, unlike JS it also has a while let loop and a loop loop. All of them respect break and continue but have a little extra spice.

for loops

We do not have the traditional for structure in rust, by that I mean

for(let i=0; i< 10; i++) { //do something }
Code language: JavaScript (javascript)

In Rust for loops are used to iterate over iterators, like arrays. I’ll write more about iterators another time but for now, it’s enough to say the structure is as follows

for i in [1,2,3,4] { // do something }
Code language: JavaScript (javascript)

while loops

These are conditional loops, i.e. loop while a condition is true.

let mut i = 0; while i < 10 { //do something i = i + 1; }
Code language: JavaScript (javascript)

So pretty much javascript without parenthesis. Rust really does have a problem with those.

while let loop

I can’t get my head around this one right now but I think that’s because I am missing some context about scrutinees and such.
I’ll have to get back to you later.

loop loop

This one is an interesting creature. It’s the first time I’ve seen the keyword loop. You can literally run it infinitely with no conditions or checks.

loop { // infinite loop stuff }
Code language: JavaScript (javascript)

But it gets better. You can return values from the loop. Yes, you read that right. You can return values from the loop.

Here is an example.

let mut counter = 0; let result = loop { counter += 1 if counter == 10 { break counter * 10; } };
Code language: JavaScript (javascript)

Since loop is an expression it returns a value. Cool!

But wait there’s more!

loop also supports labels. So for example, if you have nested loops you can break to the outer loop.

'outer_loop': loop { // outer loop stuff loop { // inner loop stuff if something { break 'outer_loop' } } }
Code language: JavaScript (javascript)

And it’s not just break, you can continue with label too.

This will take some time to get used to but so far so cool. That’s it for today, if I messed up something or if you have questions, hit me up on Twitter @phoexer, and as always happy coding.


Leave a Reply

Your email address will not be published.