Rust is a systems programming language that prioritizes performance, safety, and concurrency. It's a great language to learn if you're interested in building fast, reliable software like web servers, operating systems, or even games.
If you're looking to start programming in another language, check out these guides:
To get started with Rust, follow these steps:
rustc --version
This command should output the version of Rust installed on your system.
Create a new Rust project using cargo
, Rust's build system and package manager:
cargo new hello_rust cd hello_rust
This creates a new folder named hello_rust
with a basic project structure. Open the main.rs
file inside the src
folder and add the following code:
fn main() { println!("Hello, World!"); }
To run the program, use the command:
cargo run
This will compile and execute your program, printing Hello, World! to the console.
In Rust, variables are **immutable** by default. This means once a value is assigned to a variable, it cannot be changed. However, you can make a variable mutable by adding the mut
keyword.
fn main() { let mut count = 0; // Mutable variable count += 1; println!("Count: {}", count); // Output: Count: 1 }
By making count
mutable, you can modify its value during the program's execution. This immutability-by-default approach ensures that you don't accidentally change a variable, making your code more predictable and safe.
One of Rust's standout features is its **ownership model**, which ensures memory safety without needing a garbage collector. Here's how it works:
&
). References allow you to use a value without taking ownership of it.Here's an example of ownership in action:
fn main() { let s1 = String::from("hello"); let s2 = s1; // Ownership of the string is moved to s2 // println!("{}", s1); // This will cause an error println!("{}", s2); // Output: hello }
In this example, when s1
is assigned to s2
, ownership of the string is moved to s2
. Trying to use s1
afterward results in a compile-time error.
To avoid transferring ownership, you can **borrow** the value:
fn main() { let s1 = String::from("hello"); let s2 = &s1; // Borrowing s1 (no ownership transfer) println!("{}", s1); // Output: hello println!("{}", s2); // Output: hello }
In this case, s1
is borrowed by s2
, so both can be used without errors. Borrowing can also be mutable, allowing you to modify a value:
fn main() { let mut s = String::from("hello"); { let s_ref = &mut s; // Mutable borrow s_ref.push_str(", world!"); } println!("{}", s); // Output: hello, world! }
This ensures that only one mutable reference exists at a time, preventing data races.
Now that you've learned the basics of Rust, here are some resources to dive deeper:
Happy coding with Rust! 🚀