Welcome to our deep dive into the world of Rust! Today, we'll be exploring two powerful tools - println! and vec!. Let's get started! š
println!println! is a macro that allows you to print output to the console. It's a bit different from functions you might be used to, so let's break it down.
fn main() {
println!("Hello, World!");
}In the example above, println! is used to print the string "Hello, World!" to the console.
š” Pro Tip: The exclamation mark (!) is crucial for println!. Without it, Rust won't recognize it as a macro.
println! supports formatting with placeholders. For instance:
fn main() {
let name = "Alice";
println!("Hello, {}!", name);
}In this example, {} is a placeholder for the variable name.
vec!vec! is a shorthand for creating a new vector.
fn main() {
let numbers = vec![1, 2, 3];
}In the example above, vec! is used to create a new vector numbers with the elements 1, 2, and 3.
To access an element in a vector, you use the index operator [].
fn main() {
let numbers = vec![1, 2, 3];
let first_number = numbers[0];
println!("The first number is: {}", first_number);
}In this example, we access the first element of the numbers vector using numbers[0] and store it in the first_number variable.
š Note: Rust uses 0-indexing for vectors, meaning the first element is at index 0.
Time for some practice! Let's test your understanding with some exercises.
What does `println!` do in Rust?
How do you access the first element of a vector in Rust?