In this lesson, we'll dive deep into the world of Rust functions, focusing on parameters and arguments. This knowledge will empower you to create more complex and customizable programs! 💡
Before we delve into parameters and arguments, let's quickly review what functions are in Rust:
Parameters are the values that a function uses to perform its tasks. They are specified in the function declaration and are placeholders for the actual data that will be passed when the function is called.
// Function declaration with a parameter
fn greet(name: &str) {
println!("Hello, {}!", name);
}In the example above, greet is a function with one parameter, name, which is of type &str (a reference to a string). When we call this function with a name as an argument, it will print a personalized greeting.
Arguments are the actual values that we pass to a function when we call it. The argument values are used to replace the parameter placeholders within the function body.
// Function call with an argument
fn main() {
greet("Alice");
}In this example, we call the greet function with the argument "Alice", and the function prints the greeting Hello, Alice!.
Rust has several basic data types, including:
i32: 32-bit integeru32: 32-bit unsigned integerf32: 32-bit floating-point numberf64: 64-bit floating-point numberchar: Unicode characterbool: Boolean (true or false)String: A growable sequence of Unicode characters&str: Immutable reference to a string sliceFunctions in Rust can also return values. The return type is specified after the function name followed by the -> symbol.
fn square(num: i32) -> i32 {
num * num
}
fn main() {
let result = square(4);
println!("The square of 4 is: {}", result);
}In this example, the square function takes an i32 and returns an i32.
Functions can have multiple parameters by separating them with commas.
fn greet_with_age(name: &str, age: u32) {
println!("Hello, {}! You are {} years old.", name, age);
}
fn main() {
greet_with_age("Bob", 20);
}You can also assign default values to parameters to make function calls more flexible.
fn greet_with_optional_age(name: &str, age: u32) {
if age > 0 {
println!("Hello, {}! You are {} years old.", name, age);
} else {
println!("Hello, {}!", name);
}
}
fn main() {
greet_with_optional_age("Alice", 25);
greet_with_optional_age("Bob");
}What is the purpose of parameters in Rust functions?
Happy coding! 🤖 Let's take a break and practice what we've learned by creating our own functions with parameters and arguments. 🎉
This content is intended for CodeYourCraft and should not be copied or republished without permission.
This content is optimized for search engines and adheres to the guidelines provided.