Learn Rust from Scratch
Hello! Welcome
Today we are going to learn about Rust from Scratch
What is Rust?
Rust is a modern and safe programming language that helps us write fast and error-free code.
It is excellent for complex systems and critical applications!
Why use Rust?
Rust is designed to avoid common programming errors such as memory management failures.
This makes your code safer, without sacrificing efficiency.
Installing Rust
To get started with Rust, you need to install Rust on your computer.
You can do this by downloading the installer from the official Rust website.
So easy! Once installed on your computer, you can start using it.
You’re doing great!
Now let’s talk about hardware
Variables in Rust
Variables in Rust store information that your program uses (such as integers, floats, characters, and booleans)
let x = 5; // immutable
let mut y = 10; // mutable
let sum = 5 + 10;
With them, you can perform mathematical, logical, and comparison operations.
Conditionals
With conditionals, you can make the program make decisions. We use if
and else
to execute code only if a condition is true.
For example:
if x > 5 {
println!("Is greater than 5");
}
Loops
Loops allow us to repeat actions and iterate over ranges and collections. For example, loop
, while
, and for
.
for i in 0..5 {
println!("{}", i);
}
Functions in Rust
Functions are blocks of code that perform specific tasks.
fn sum(a: i32, b: i32) -> i32 {
a + b
}
You can use functions to organize your code and make it easier to understand.
Arrays and collections
Collections are structures that allow you to store multiple values. The simplest is an array.
let arr = [1, 2, 3, 4, 5]; // array
let vec = vec![1, 2, 3]; // vector
We also have vectors, which are more flexible because they can change size dynamically.
Structures in Rust
Structures are a way to group related data. With them, you can create custom data types for your program.
struct Person {
name: String,
age: u8,
}
They are useful for modeling entities with multiple properties.
Error handling
Rust uses Result
and Option
to handle errors safely and avoid issues in your code.
let result: Result<i32, &str> = Ok(10);
This helps to prevent runtime errors.
You’re almost there!
We just need to see how to program your Arduino
Creating a project in Rust
To create a Rust project, we use Cargo, the Rust tool for managing projects.
cargo new my_project
cd my_project
Write your first program in Rust
A good first project in Rust is to write a program that displays a message on the screen.
fn main() {
println!("Hello, Rust!");
}
Modify main.rs
to write your first program
Compile and run
Once your code is ready, compile it with Rust and run the program to see the result.
cargo run
Cargo will take care of compiling and running your code.
Well done!
Now you know the basics of Rust Keep exploring the language!