Variables

Binding and mutability

  1. 🌟 A variable can be used only if it has been initialized.
2. // Fix the error below with least amount of modification to the code
3. fn main() {
4. let x: i32; // Uninitialized but used, ERROR !
5. let y: i32; // Uninitialized but also unused, only a Warning !

7. assert_eq!(x, 5);
8. println!("Success!");
9. }
  1. 🌟 Use mut to mark a variable as mutable.
2. // Fill the blanks in the code to make it compile
3. fn main() {
4. let __ __ = 1;
5. __ += 2;

7. assert_eq!(x, 3);
8. println!("Success!");
9. }

Scope

A scope is the range within the program for which the item is valid.

  1. 🌟
2. // Fix the error below with least amount of modification
3. fn main() {
4. let x: i32 = 10;
5. {
6. let y: i32 = 5;
7. println!("Inner scope value of x is {} and value of y is {}", x, y);
8. }
9. println!("Outer scope value of x is {} and value of y is {}", x, y);
10. }
  1. 🌟🌟
2. // Fix the error with the use of define_x
3. fn main() {
4. println!("{}, world", x);
5. }

7. fn define_x() {
8. let x = "hello";
9. }

Shadowing

You can declare a new variable with the same name as a previous variable, here we can say the first one is shadowed by the second one.

  1. 🌟🌟
2. // Only modify `assert_eq!` to make the `println!` work(print `42` in terminal)
3. fn main() {
4. let x: i32 = 5;
5. {
6. let x = 12;
7. assert_eq!(x, 5);
8. }

10. assert_eq!(x, 12);

12. let x = 42;
13. println!("{}", x); // Prints "42".
14. }
  1. 🌟🌟
2. // Remove a line in the code to make it compile
3. fn main() {
4. let mut x: i32 = 1;
5. x = 7;
6. // Shadowing and re-binding
7. let x = x;
8. x += 3;

10. let y = 4;
11. // Shadowing
12. let y = "I can also be bound to text!";

14. println!("Success!");
15. }

Unused variables

  1. Fix the warning below with :

  2. 🌟 Only one solution

  3. 🌟🌟 Two distinct solutions

Note: none of the solutions is to remove the line let x = 1

2. fn main() {
3. let x = 1;
4. }

6. // Warning: unused variable: `x`

Destructuring

  1. 🌟🌟 We can use a pattern with let to destructure a tuple to separate variables.

Tips: you can use Shadowing or Mutability

2. // Fix the error below with least amount of modification
3. fn main() {
4. let (x, y) = (1, 2);
5. x += 2;

7. assert_eq!(x, 3);
8. assert_eq!(y, 2);

10. println!("Success!");
11. }

Destructuring assignments

Introduced in Rust 1.59: You can now use tuple, slice, and struct patterns as the left-hand side of an assignment.

  1. 🌟🌟

Note: the feature Destructuring assignments need 1.59 or higher Rust version

2. fn main() {
3. let (x, y);
4. (x,..) = (3, 4);
5. [.., y] = [1, 2];
6. // Fill the blank to make the code work
7. assert_eq!([x,y], __);

9. println!("Success!");
10. }

You can find the solutions here(under the solutions path), but only use it when you need it