w3resource

Rust Program: Variable assignment

Rust Basic: Exercise-11 with Solution

Write a Rust program that creates two variables p and q, assigns a value to p, then assigns p to q and try to use p again.

Sample Solution:

Rust Code:

fn main() {
    // Declare variable 'p' and initialize it with a value
    let p = 10;

    // Declare an unused variable '_q' instead of 'q'
    let mut _q;

    // Assign the value of 'p' to '_q'
    _q = p;

    // The following line will print the value of 'p'
    println!("Value of p: {}", p);
}

Output:

Value of p: 10

Explanation:

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

  • fn main() { ... }: This is the entry point of the program, where execution begins.
  • let p = 10;: This line declares a variable named 'p' and initializes it with the value 10.
  • let mut q;: This line declares a mutable variable named 'q' without initializing it. It's declared but not used in this code, hence the warning message about an unused variable.
  • q = p;: This line assigns the value of variable 'p' to variable 'q'. This is allowed because 'p' hasn't been borrowed or moved elsewhere.
  • println!("Value of p: {}", p);: This line prints the value of variable 'p' using the println! macro. The {} is a placeholder for the value of 'p', which is provided as an argument to the println! macro. Since 'p' is borrowed immutably for printing, it's still accessible even after being assigned to '_q'.

Rust Code Editor:

Previous: Rust Program: Factorial calculation.
Next: Rust Function: Modify variable reference.

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.