Let's Rust (4th part): Fizzbuzz in Rust. And more

in-n-out.cloud
LetsRust
Published in
5 min readFeb 20, 2023

I'm only beginning to code in Rust, and I still need to learn many parts of the Rust syntax, but I enjoy writing working code. So here we go, only a 3rd part, but #letsRust some for a "FizzBuzz" coding exercise.

FizzBuzz implementation logic

Using FizzBuzz, I aim to write a simple program that supplies the number as the parameter. My simple program (just some working code* ;) ) will print “Stand With” if the number contains "3", print “Ukraine” if the number contains "5", and “Stand With Ukraine” if the number contains "3", and "5". The range of numbers is from 1 to 15 (inclusively ).

I will be using this acronym moving forward JSWC

The Program ( just some working code — JSWC)

By now, we all know what cargo is. But if I still need to, I gotchu here. So let’s start:

~/letsrust  =>cargo init p3_fizzbuzz
Created binary (application) package
~/letsrust/p3_fizzbuzz =>ll
total 16
drwxr-xr-x 6 devnull staff 192B Jan 4 00:08 ./
drwxr-xr-x 5 devnull staff 160B Jan 4 00:08 ../
drwxr-xr-x 9 devnull staff 288B Jan 4 00:08 .git/
-rw-r--r-- 1 devnull staff 8B Jan 4 00:08 .gitignore
-rw-r--r-- 1 devnull staff 180B Jan 4 00:08 Cargo.toml
drwxr-xr-x 3 devnull staff 96B Jan 4 00:08 src/

As a Python developer, the implementation logic looked like the below to get me started with some code. There are more efficient solutions than this, but they are simple and work.


fn main() {
for x in 1..=15 {
if x % 3 == 0 && x % 5 == 0 {
println!("Stand With Ukraine!")
} else if x % 3 == 0 {
println!("Stand With")
} else if x % 5 == 0 {
println!("Ukraine!")
} else {
println!("{}", x)
}
}
}

The output will look like this:

~/letsrust/p3_fizzbuzz 🦕 =>cargo run
Compiling p3_fizzbuzz v0.1.0 (/Users/devnull/letsrust/p3_fizzbuzz)
Finished dev [unoptimized + debuginfo] target(s) in 0.67s
Running `target/debug/p3_fizzbuzz`
1
2
Stand With
4
Ukraine!
Stand With
7
8
Stand With
Ukraine!
11
Stand With
13
14
Stand With Ukraine!
~/letsrust/p3_fizzbuzz 🦕 =>

From the above, just some working code, I can still learn how to use iterative operations in the code (using for loop in the current example). And I start understating how if-else conditions are used in n Rust.

loops

Rust currently has support for the five loop expressions ( I will be posting another blogpost about loops only )

  • loop expression
  • for expression
  • while expression
  • while let expression
  • labelled block expression

for loop expression

The for loop in Rust extracts a series of values from an iterator, looping until the iterator is empty (this logic is similar to most system programming languages). Rust language supports using for loop inside the for a loop.

Inside for expression, a break and continue statements are supported to control the loop flow.

Syntax

for any_variable in start_point..upperend_point {
// some code block to execute with cool logic you are writing
}
  • For a keyword is how the expression begins.
  • any_ariable a temporary variable ( naming convention according to Rust syntax for variable names)
  • start_value..end_value is a range syntax that defines the number of times the loop should be executed.
//from my fizzbuzz code example
for x in 1..=15 {
//some cool logic of yours
println!("Stand With Ukraine!")
}

if-else expression

Using if-else conditional flow expression is similar to other languages (at least languages I use to program :) ). In programming languages, conditional flow (where the condition is true or false) is used to implement the decision-making logic for non-trivial programs.

Syntax:

if statement

if condition {
// some code block to execute, with cool logic you are writing
// if condition proves true
}

The boolean if condition in Rust doesn’t need to be surrounded by parentheses, and a block must follow each condition. Multiple conditions can be used with the logical operators AND and OR ( && and || ). All conditions must prove true before the code will execute.

// if also 
if condition_1 && condition_2 {
// some code block to execute, with cool logic you are writing
// if both conditions prove true
}

if-else statement

if condition {
// some code block to execute, with cool logic you are writing
// if condition proves true
}
else if {
// some code block to execute, with cool logic you are writing
// if condition proves true
}

if-else conditionals expressions I use mostly when writing code with multiple types of conditions that do not fit within a single if condition. Rust supports writing many if statements and combining them into if-else“branches”; all “branches” must return the same type.

To write a conditional else if statement, add another if statement below the first, separated by the else keyword. The compiler will evaluate each if statement in the “branches” when done with the previous one.

else statement

The else statement works as a catch-all fallback for anything not covered by an if statement or else-if“branches.” Because it acts as a catch-all, the else statement doesn’t have a conditional block, only an execution code block.

if condition {
// some code block to execute, with cool logic you are writing
// if condition proves true
}
else if {
// some code block to execute, with cool logic you are writing
// if condition proves true
}
else {}

In Rust looks like I can ( I didn’t find any mentions of the limitations yet) use as many else if statements in “branches” as I need.

if x % 3 == 0 && x % 5 == 0 {
println!("Stand With Ukraine!")
} else {
println!("{}", x)
}

match() expression

After reading Rust Design Patterns and understanding the for-loop implementation I found a recommendation using a control flow construct called match(). If you are coming from Python or C background, it feels similar to the switch()statement.

fn main() {
for x in 1..=15 {
match x {

x if x % 3 == 0 => println!("{} Stand With ", x),
x if x % 5 == 0 => println!("{} Ukraine!", x),
// Multiple matches using the | operator
x if (x % 3 == 0) | (x % 5 == 0) => println!("{} Stand With Ukraine!", x),
// Handle the rest of the cases
_ => println!("{}", x),
}
}
}

The output of jmwc using match()will look like this:

~/letsrust/p3_fizzbuzz 🦕 =>cargo run
Compiling p3_fizzbuzz v0.1.0 (/Users/devnull/letsrust/p3_fizzbuzz)
Finished dev [unoptimized + debuginfo] target(s) in 0.48s
Running `target/debug/p3_fizzbuzz`
1
2
3 Stand With
4
5 Ukraine!
6 Stand With
7
8
9 Stand With
10 Ukraine!
11
12 Stand With
13
14
15 Stand With
~/letsrust/p3_fizzbuzz 🦕 =>

In the above, the match() operator takes in a variable and compares its value with each case value. If there is a match, the corresponding block of code is executed.Match() also can have a default case.

My useful notes:

Note 1: In Rust language, there is a loop keyword to indicate an infinite loop used to define the simplest kind of loop supported

Note 2: Note that an else if statement can only follow an if statement it cannot stand on its own. The first conditional must always be an if.

Note 3: The safety and conciseness of forloops make them the most commonly used loop construct in Rust.

Note 4: Match() can be used like an expression, it can be assigned to a variable.

--

--

in-n-out.cloud
LetsRust

Staff Cloud Engineer working on k8s, cloud, microservices. Millennial. Coffeholik. Started #LetsRust on medium