Rust Tutorials: Understanding Return Values 🎯

beginner
21 min

Rust Tutorials: Understanding Return Values 🎯

Welcome to the Rust Tutorial Series! 🚀

In this tutorial, we'll dive deep into Return Values – an essential concept in programming that allows functions to communicate results back to the calling code. By the end of this tutorial, you'll understand how to use return values effectively in Rust. 💡

Table of Contents 📝

  1. Basics of Return Values
  2. Functions with Return Values
  3. Returning Multiple Values
  4. Quiz: Test Your Knowledge

Basics of Return Values 📝

Every function in Rust can return a value when it completes its execution. This value is used by the calling code to understand the result of the function execution. The return keyword is used to specify the value that a function returns.

rust
fn greet() -> String { String::from("Hello, World!") }

In the example above, we have a function called greet() which returns a String value.


Functions with Return Values 📝

To understand functions with return values, let's create a simple function that calculates the square of a number:

rust
fn square(num: i32) -> i32 { num * num }

In this example, the function square accepts an i32 (32-bit integer) as an argument and returns an i32. We can call this function in our main function and print the result:

rust
fn main() { let result = square(4); println!("{}", result); }

In the main function, we call the square function with the argument 4, store the result in the result variable, and then print the result.


Returning Multiple Values 📝

Rust doesn't allow functions to return multiple values directly. However, we can use tuples to achieve this.

rust
fn get_coordinates(point: (i32, i32)) -> (i32, i32) { point }

In the example above, the get_coordinates function takes a tuple as an argument and returns the same tuple. Now, we can call this function with a point and print its coordinates:

rust
fn main() { let point = (3, 4); let coordinates = get_coordinates(point); println!("X: {}, Y: {}", coordinates.0, coordinates.1); }

In the main function, we call the get_coordinates function with a point (3, 4) and print the coordinates using the .0 and .1 syntax.


Quiz: Test Your Knowledge 🎯

Quick Quiz
Question 1 of 1

Which keyword is used to specify the value that a function returns in Rust?


Conclusion 📝

Understanding return values is crucial when working with functions in Rust. Functions can return single or multiple values, and the return keyword is used to specify the value that a function returns.

In the next tutorial, we'll explore more advanced concepts in Rust programming. Stay tuned! 🎯