Welcome to the Function Syntax lesson in Rust! In this tutorial, you'll learn how to define and use functions, one of the fundamental concepts in the Rust programming language. Let's dive in!
In simple terms, a function is a block of code that performs a specific task. Functions are used to organize code, make it reusable, and simplify complex problems.
To create a function in Rust, you use the fn keyword, followed by the function name, and curly braces {} to enclose the function's body. Here's an example of a simple function:
fn greet(name: &str) {
println!("Hello, {}!", name);
}š” Pro Tip: &str is a reference to a string literal, meaning we're passing a string to the function.
Now that we have defined the function, let's call it!
To call a function in Rust, simply use the function name followed by parentheses (). You can pass arguments, if any, inside the parentheses.
greet("Alice");This will output: Hello, Alice!
Functions can also return values. The return type is specified after the function name, followed by an arrow ->. Here's an example of a function that returns the length of a string:
fn string_length(s: &str) -> i32 {
s.len()
}Now, let's call this function:
let length = string_length("Rust is fun!");
println!("The length of the string is: {}", length);This will output: The length of the string is: 17
Now that you've learned the basics of functions, let's put your new skills to the test!
What does the `fn` keyword do in Rust?
What is the purpose of the curly braces `{}` in a Rust function?
Keep practicing, and you'll master functions in no time! In the next lesson, we'll explore more advanced topics in Rust. Happy coding! šš»