Function Syntax in Rust Tutorial šŸš€

beginner
12 min

Function Syntax in Rust Tutorial šŸš€

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!

What are Functions? šŸ’”

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.

Defining a Function šŸ“

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:

rust
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!

Calling a Function šŸŽÆ

To call a function in Rust, simply use the function name followed by parentheses (). You can pass arguments, if any, inside the parentheses.

rust
greet("Alice");

This will output: Hello, Alice!

Function Return Types āœ…

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:

rust
fn string_length(s: &str) -> i32 { s.len() }

Now, let's call this function:

rust
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

Practice Time šŸ“

Now that you've learned the basics of functions, let's put your new skills to the test!

Quick Quiz
Question 1 of 1

What does the `fn` keyword do in Rust?

Quick Quiz
Question 1 of 1

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! šŸš€šŸ’»