w3resource

Rust Function: Modify variable reference

Rust Basic: Exercise-12 with Solution

Write a Rust function that takes a reference to a variable as a parameter and modifies its value.

Sample Solution:

Rust Code:

// Define a function named 'modify_value' that takes a mutable reference 'value' of type i32
fn modify_value(value: &mut i32) {
    // Increment the value by 1
    *value += 1;
}

fn main() {
    // Declare a variable 'num' and initialize it with a value
    let mut num = 5;

    // Call the 'modify_value' function and pass a mutable reference to 'num'
    modify_value(&mut num);

    // Print the modified value of 'num'
    println!("Modified value of num: {}", num); // Output will be 6
}

Output:

Modified value of num: 6

Explanation:

Here's a brief explanation of the above Rust code:

  • fn modify_value(value: &mut i32) { ... }: This line defines a function named 'modify_value' that takes a mutable reference value of type i32 as a parameter. Inside the function, it increments the value by 1 using the dereference operator *.
  • value += 1;: This line increments the value that value points to by 1. Since value is a mutable reference, we need to use the dereference operator to access and modify the value it refers to.
  • fn main() { ... }: This is the entry point of the program, where execution begins.
  • let mut num = 5;: This line declares a mutable variable 'num' and initializes it with the value 5.
  • modify_value(&mut num);: This line calls the "modify_value()" function and passes a mutable reference to 'num' using the '&mut' operator. This allows the function to modify the value of 'num' directly.
  • println!("Modified value of num: {}", num);: This line prints the modified value of 'num' after calling the "modify_value()" function. The modified value will be 6, as it was incremented by the function.

Rust Code Editor:

Previous: Rust Program: Variable assignment.
Next: Rust Function: Find smallest string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.