Rust: Strings, Loops, Conditional statements Basics — A Practical Guide

Strings, Loops, Conditional statements

Yash
4 min readJan 15, 2024
By author

Hello Codes! 👋🐍 Welcome back to our exploration of Rust. In our previous blog, we deep dived into Rust’s data types, and now it’s time to roll up our sleeves and get hands on with the language’s core syntax, will also compare it with Python syntax. No frills, just practical insights to make your transition smoother. 🚀🦀

1. Assigning Variables and Handling Strings 📝

In Rust, variable assignment and string handling are straightforward yet fine. Let’s break it down:

Rust

let name = String::from("Pythonista");
let age = 28;
println!("Hello, I'm {} and I'm {} years old!", name, age);
  • Here, we declare a string variable ‘name’ and an integer variable ‘age’.
  • The ‘println!’ macro prints a formatted string using these variables.
  • Rust’s ownership system ensures memory safety without sacrificing performance.

Python

name = "Pythonista"
age = 28
print(f"Hello, I'm {name} and I'm {age} years old!")

Rust vs. Python: While both languages use simple syntax for variable assignments and string interpolation, Rust’s String::from introduces ownership, ensuring memory safety without a garbage collector.

Python’s simplicity shines here, but Rust’s approach prioritizes control and predictability.

2. Lists, Tuples, and Dictionaries: Building Your Data Arsenal 🧰

Rust provides versatile data structures to suit different needs:

  • Vectors: Dynamic, growable lists that are efficient and memory-safe.
  • Tuples: Immutable collections of fixed size, useful for grouping related data.
  • HashMaps: Key-value pairs for efficient data organization.

Rust

let my_vector = vec![1, 2, 3];
let my_tuple = (4, 5);
let mut my_dict = HashMap::new();
my_dict.insert("name", "RustExplorer");
my_dict.insert("level", "Intermediate");
  • These structures offer flexibility and control over your data, with Rust's ownership system ensuring safety.

Python

my_list = [1, 2, 3]
my_tuple = (4, 5)
my_dict = {'name': 'Pythonista', 'level': 'Expert'}

Rust vs. Python: Rust’s structures align with Python’s, but Rust adds a layer of control with its ownership system.

While Python leans into ease of use, Rust ensures safety with a more explicit approach to memory management.

3. Conditional Statements: Shaping Code Paths 🛠️

Conditional statements in Rust are familiar yet robust:

Rust

let temperature = 25;
if temperature > 30 {
println!("It's a hot day!");
} else {
println!("Enjoy the pleasant weather.");
}
  • By using ‘if/else’, you guide your program’s logic. Rust’s strict ownership rules ensure predictability in managing resources.

Python

temperature = 25

if temperature > 30:
print("It's a hot day!")
else:
print("Enjoy the pleasant weather.")

Rust vs. Python: The conditional structures in both languages feel similar, but Rust’s strict ownership subtly influences how we think about managing resources.

Python prioritizes ease of use, while Rust emphasizes predictability in memory handling.

4. Loops: Mastering Iteration 🔄

Looping constructs in Rust are powerful tools for repetitive tasks, let’s see different types of loops in Rust:

Infinite Loop

loop {
// Code to repeat indefinitely
}

An infinite loop keeps executing its body continuously until manually interrupted.

Predicate Loop

let mut i = 0;
while i < 10 {
println!("hello");
i = i + 1;
}

A while loop executes its body as long as the specified condition remains true.

Predicate Pattern Loop

let mut x = vec![1, 2, 3];
while let Some(y) = x.pop() {
println!("y = {}", y);
}

A while let loop allows pattern matching while iterating over an option or result.

Iterator Loop

let v = &["apples", "cake", "coffee"];
for text in v {
println!("I like {}.", text);
}

A for loop iterates over items provided by an iterator until it's exhausted.

Labelled Block Loop

'outer: loop {
// Code to run once but breakable with labels
break 'outer;
}

A labelled block loop runs its body once but allows breaking out early with labels.

Rust ‘for’ & ‘while’ Loop Example

for number in 0..5 {
println!("This is iteration {}", number);
}
let mut counter = 0;
while counter < 3 {
println!("Looping... Round {}", counter);
counter += 1;
}
  • Whether it’s a simple ‘for’ loop or a more dynamic ‘while’ loop, Rust’s syntax allows for precise control over iteration.

Python

for number in range(5):
print(f"This is iteration {number}")

counter = 0
while counter < 3:
print(f"Looping... Round {counter}")
counter += 1

Rust vs. Python: Both languages provide constructs for iteration, but Rust’s loops bring explicitness and control, reinforcing the language’s commitment to predictability in resource handling.

Wrapping Up: Rust in the Real World 🌐

In summary, Rust's syntax is pragmatic and designed for practical application. It aligns efficiency with safety, making it a compelling choice for developers seeking both speed and reliability in their projects.

As we continue this Rust journey together, share your insights and questions. I'm navigating Rust's waters alongside you, and your experiences add valuable perspectives.

I’m still learning Rust myself, so we can dive into this together..🤜🤛..Looking forward to sharing more about Rust with you soon…😎

Until then happy coding, Rust explorers! 🚀🦀

Click ➡️ subscribe if you want to see more content like this, your support 🫶 fuels me to keep writing! 🌟🧑‍💻🚀

By https://www.instagram.com/yashtishaskyscapes?igsh=amp3M3NpZng3czNm

--

--

Yash

I'm a Data Scientist & Renewable Energy geek 🌱 Exploring Data📊, Green tech🌍, and Innovation💡 Hope to write on Data Science, Life, & Everything in between ;)