Learn Rust from Scratch Educative Quiz Answers

Get Learn Rust from Scratch Educative Quiz Answers

The word is out: developers love Rust. It’s quickly becoming one of the most popular languages among systems and embedded programmers, and the demand for Rust developers is growing considerably. It’s a very powerful language in terms of performance, reliability, and productivity, especially when compared to C++. If you’re a system developer looking for a new language to learn, then Rust is a great place to look next.

In this course, you’ll be able to learn Rust while getting your hands dirty along the way. It begins with a simple “Hello world” program and proceeds to cover common concepts such as Arrays, Strings, Vectors, Enums, Structures, Traits, Generic, Functions, and Logic. Finally, it dives deeper into more advanced concepts like Lifetime and memory management.

By the time you’re done, you’ll have a good grip on the basics of Rust, and will be ready to move on to more advanced concepts.

Enroll on Educative

Quiz 1: The Basic Program

Q1. What is the key word for declaring a function?

  • fun
  • func
  • fn
  • func

Q2. What is the output of the following code?

fn main() {
    println!("Hello World!")
    println!("Hello");
}
  • Hello World!
    • Hello
  • Error

Quiz 2: The Basic Formatting

Q1. What is the output of the following code?

fn main() {
    println!("Enhance your coding skills from {1} courses.  {0} courses are very {1}", "Educative", "interactive");
}
  • Enhance your coding skills from Educative courses. Educative courses are very interactive
  • Enhance your coding skills from interactive courses. Educative courses are very interactive

Q2. What is the output of the following code?

fn main() {
    println!("{}{}", 2, 1);
}
  • 21
  • 12

Quiz 3: Printing Styles

Q1. Which of the following print statement appends a new line to the output?

  • Option 1
print!("Rust");
  • Option 2
println!("Rust");
  • Option 3
eprint!("Rust");
  • Option 4
eprintln!("Rust");

Q2. Which of the following is used to display an error?

  • Option 1
eprint!("Rust");
  • Option 2
eprintln!("Rust");
  • Option 3
print!("Rust");
  • Option 4
println!("Rust");

Q3. What is the output of the following code?

fn main() {
    println!("Learning language :");
    print!("Rust");
    print!("Programming");
    print!("Language");
}
  • Learning language :
    • RustProgrammingLanguage
  • Learning language :
    • Rust
    • Programming
    • Language

Quiz 4: Comments

Q1. Which type of comment is this? //

  • Line
  • Doc

Q2. Which comment supports markdown notation?

  • Line comment
  • Doc comment

Challenge 1: Display Output

Answer:

fn test() {
    print!("I am learning Rust programming language");
}

Challenge 2: Display Output Using Placeholders

Answer:

fn test() {
    println!("{}", 1);
    println!("{}{}", 2, 2);
    println!("{}{}{}", 3, 3, 3);
    println!("{}{}{}{}", 4, 4, 4, 4);
    println!("{}{}{}{}{}", 5, 5, 5, 5, 5);
}

Quiz 5: What Are Variables?

Q1. Which one is not a property of a default variable?

  • mutability
  • store primitive data
  • store reference to a data

Q2. Which of the following code snippets help to make a mutable variable?

  • Option 1
let course_name = "Rust";
  • Option 2
let mut course_name = "Rust";

Quiz 6: Scope and Shadowing

Q1. A variable cannot be accessed outside it’s scope.

  • True
  • False

Q2. What is the output of the following code?

fn main(){
   let a=1;
  {
         let b=1;
  }
  println!("The value of b is {}",b);
}
  • The value of b is 1
  • Compile time error

Q3. A variable that takes the same name in the inner block as that of variable in the outer block. This concept is called

  • Scope of a variable
  • Shadowing

Challenge 3: Defining Variables

Answer:

fn test() {
    // declare a mutable variable `x`
    let mut x = 1000;
    // declare a variable `y`
    let y="Programming";
    // print output of `x`
    println!("x:{}", x);
    // print output of `y`
    println!("y:{}", y);
    // update x
    x = 1100;
    // print output of `x`
    println!("x:{}", x);
    // print output of `y`
    println!("y:{}", y);
}

Quiz 7: What Are Data Types?

Q1. Which of the following is a scalar data type?

  • Integer
  • Float
  • Tuple
  • Array

Q2. In Rust it is a must to define the type of the variable.

  • True
  • False

Quiz 8: Numeric Types: Integers and Floats

Q1. What is the data type of the variable below?

 let  a = 123;
  • Integer
  • Float

Q2. Which of the following is an incorrect notation to declare a float type variable?

  • f32
  • f64
  • f128

Quiz 9: Boolean

Q1. What is the output of the following code?

let value = 13 > 20;
println!("{}", value);
  • True
  • False

Quiz 10: Character and String

Q1. What is the output of the following code?

let value:str = "Rust Programming";
println!("{}", value);
  • Rust Programming
  • Error

Q2. What is the valid syntax for defining a character explicitly?

  • Option 1
let char1 : char = 'e';
  • Option 2
let char1: character = 'e';

Quiz 11: Arrays

Q1. How can you define an array in rust?

  • Option 1
let arr: [i32;4] = [1,2,3,4];
  • Option 2
let arr: [i32:4] = [1,2,3,4];

Q2. What is the output of the following code?

let arr:[i32;4] = [1,2,3,4]; 
let slice_array:&[i32] = &arr[0..1];
println!("Slice of an array : {:?}", slice_array);
  • Slice of an array : [1, 2]
  • Slice of an array : [1]

Quiz 12: Tuples

Q1. Which of the following statements is not true?

  • Tuple is immutable by default
  • Array is immutable by default
  • Tuple can never be made mutable
  • Array can never be made mutable

Q2. What is the output of the following code snippet?

let (w ,x, y, z) = ("1","3","2","4");
println!("w : {}",w);
println!("x : {}",x);
println!("y : {}",y);
println!("z : {}",z);
  • w : 1
    • x : 3
    • y : 2
    • z : 4
  • w : 1
    • x : 2
    • y : 3
    • z : 4

Challenge 4: Declare an Array

Answer:

fn test() {
    // define an array
    let arr:[i32;6] = [0,2,4,6,8,10]; 
    // print the values of array
    print!("{},{},{},{},{},{}",arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]);
}

Challenge 5: Declare a Tuple

Answer:

fn test() {
    // define a tuple
    let persons = ("Alex",21, "Abe", 22, "Anna", 23);
    // print values of tuple
    print!("{}:{}, {}:{}, {}:{}", persons.0, persons.1, persons.2, persons.3, persons.4, persons.5);
}

Quiz 13: Arithmetic Operators

Q1. What is the output of the following code?

fn main() {
  let mut a = 4;
  let mut b = 3;
  a = a + b;
  a = a * b;
  a = a - b;
  b = b - a;
  println!("a:{}", a);
  println!("b:{}", b);
   
}
  • a:18
    • b:-15
  • a:15
    • b:18
  • a:18
    • b:15
  • a:-18
    • b:-15

Quiz 14: Logical Operators

Q1. What is the output of the following code?

fn main() {
  let mut a = false;
  let mut b = true;
  a = a && b || ( ! a);
  b = !b;
  println!("a:{}", a);
  println!("b:{}", b); 
}
  • a:false
    • b:true
  • a:true
    • b:false
  • a:true
    • b:true
  • a:false
    • b:false

Quiz 15: Comparison Operators

Q1. What is the output of the following code?

fn main() {
  let mut a = true;
  let mut b = true;
  a = a > b && b < a;
  b = !b;
  println!("a: {}", a);
  println!("b: {}", b); 
}
  • a:false
    • b:true
  • a:true
    • b:false
  • a:true
    • b:true
  • a:false
    • b:false

Quiz 16: Bitwise Operators

Q1. What is the output of the following code?

fn main() {
  let mut a = 1;
  let mut b = 2;
  a = a & b;
  a = a << 1;
  b = b >> 3;
  println!("a: {}", a);
  println!("b: {}", b); 
}
  • a: 0
    • b: 2
  • a: 0
    • b: 0
  • a: 2
    • b: 0
  • a: 2
    • b: 2

Quiz 17: Assignment and Compound Assignment Operators

Q1. What is the output of the following code?

fn main() {
  let mut a = 2;
  let mut b = 3;
  a += a;
  b -= b;
  a *= 1;
  b *= 3;
  a -= 1;
  println!("a: {}", a);
  println!("b: {}", b); 
}
  • a: 3
    • b: 0
  • a: 0
    • b: 3
  • a: 2
    • b: 0
  • a: 4
    • b: 3

Quiz 18: Type Casting Operator

Q1. What is the output of the following code?

fn main() {
    let a = 15;
    let b = (a as f32) / 3.0; 
    println!("a:{}",a);
    println!("b:{}",b);
}
  • a:15
    • b:7.5
  • a:15
    • b:5

Quiz 19: Borrowing and Dereferencing Operators

Q1. A variable can be updated through a dereference operator if it’s a

  • shared borrow
  • mutable borrow

Q2. What is the output of the following code?

fn main() {
      let a = &10;
      let b = &mut 9;
      *b = 12;
      println!("Value of a:{}",a);
      println!("Value of b:{}",b);   
}
  • Option 1
Value of a:10
Value of b:12
  • Option 2
Value of a:10
Value of b:9

Quiz 20: Precedence and Associativity

Q1. What is the output of the following code according to its operator precedence in Rust?

fn main() {
    println!("{}", 3 + 4 - 9 / 6 * 6 ^ 8 & 3);
}
  • 1
  • 2
  • 3
  • 4

Challenge 6: Calculate (a + b)^3

Answer:

fn test() {
    let a = 2;
    let b = 2;
    let c = i32::pow(a,3) + i32::pow(b, 3) + ( 3 * a * b * (a + b)) ;
    println!("{}", c);  
}

Quiz 21: If Expression

Q1. What is the output of the following code?

fn main() {
   let age=23; 
   if age >=21{ 
      println!("Age is greater than 21");
   }
    else if age <21{
       println!("Age is less than 21");
    }
    println!("Value Printed");
}
  • Age is greater than 21
    • Value Printed
  • Age is less than 21
    • Value Printed
  • Age is greater than 21
  • Age is less than 21

Q2. Which If block is executed?

 fn main() {
   let age=23; 
   let play=true; 
   let activity="Tennis" ;
   if age >=21 && play==false && activity=="Tennis"{ 
     println!("Age is greater than 21");
     println!("You are not allowed to play");
     println!("The sport is {}",activity);
   }
   else if  age >=21 && play==true && activity=="Tennis"{ 
     println!("Age is greater than 21");
     println!("You are allowed to play");
     println!("The sport is {}",activity);
   }
   else if age <21 && play==false && activity=="Tennis"{
     println!("Age is less than 21");
     println!("You are allowed to play");
     println!("The sport is {}",activity);
   }
   else {
     println!("Value Printed");
   }
}
  • First
  • Second
  • Third

Q3. What is the output of the following code?

fn main() {
  let age = 23; 
  let play = true; 
  let activity="Baseball" ;
  if age >= 21 && play==true || activity == "Tennis" { 
    println!("Age is greater than 21");
    println!("You are allowed to play");
    println!("The sport is {}",activity);
  }
  else if  age >= 21 && play == true && activity == "Tennis"{ 
    println!("Age is greater than 21");
    println!("You are allowed to play");
    println!("The sport is {}",activity);
  }
  else if age <21 && play == false && activity == "Tennis"{
    println!("Age is less than 21");
    println!("You are allowed to play");
    println!("The sport is {}",activity);
  }
  else{
    println!("Value Printed");
  }
 }
  • Age is greater than 21
    • You are allowed to play
    • The sport is Baseball
  • Age is greater than 21
    • You are allowed to play
    • The sport is Tennis

Quiz 22: If Let Expression

Q1. What is the output of the following code?

fn main() {    
    let course = ("Rust", "beginner","course");
    if let ("Rust", "beginer","course") = course {
        println!("Wrote all values in pattern to be matched with the scrutinee expression");
    } else {
        println!("Value unmatched");
    }
}
  • Wrote all values in pattern to be matched with the scrutinee expression
  • Value unmatched

Q2. What is the output of the following code?

fn main() {
    // no pattern is defined
    if let _ = 10 {
        println!("irrefutable if-let pattern");
    }
}
  • Gives a warning with output irrefutable if-let pattern
  • No warning with output irrefutable if-let pattern

Quiz 23: Match Expression

Q1. What is the output of the following code?

fn main() {
  let x = 21;

  match x {
      1 => println!("Java"),
      2 => println!("Python"),
      3 => println!("C++"),
      4 => println!("C#"),
      5 => println!("Rust"),
      6 => println!("Kotlin"),
      _ => println!("Some other value"),
  }
}
  • Python
    • Java
  • Some other value

Q2. What is the output of the following code?

fn main() {
  let mut x = 2;
  match x {
      1 => println!("Java"),
      2 => println!("Python"),
      3 => println!("C++"),
      4 => println!("C#"),
      5 => println!("Rust"),
      6 => println!("Kotlin"),
      _ => println!("Some other value"),
  }
  x = 1;
  match x {
      1 => println!("Java"),
      2 => println!("Python"),
      3 => println!("C++"),
      4 => println!("C#"),
      5 => println!("Rust"),
      6 => println!("Kotlin"),
      _ => println!("Some other value"),
  }
}
  • Python
    • Java
  • Some other value
  • Java
    • Python

Challenge 7: Check If Even or Odd

Answer:

fn test(_a:i32){
    if _a % 2 == 0{
      print!("Number {} is even", _a);
    }
    else{
      print!("Number {} is odd", _a);
    }
}

Challenge 8: Make a Calculator

Answer:

fn test(a: i32, operator: char ,b: i32) {
    match operator {
            '+' => {
                println!("{}", a + b);
            },
            '-' => {
                println!("{}", a - b);
            },
            '*' => {
                println!("{}", a * b);
            },
            '/' => {
                if b == 0{
                    println!("Division by 0 is undefined");
                }
                else {
                    println!("{}", a / b);
                }
            },
            '%' => {
                println!("{}", a % b);
            },
            _ => println!("{}","invalid operator"),
        }
}

Quiz 24: Definite Loop – For Loop

Q1. What is the output of the following code?

fn main() {
  for i in 0..5{
     if i % 4 == 0 {
        print!("{}", i);
     }
  }
}
  • Option 1
04
  • Option 2
01234

Q2. What is the output of the following code?

fn main() {
  for (count, variable) in (7..10).enumerate() {
       if count * 2 == 4{
      println!("count = {}, variable = {}", count, variable);
       }
  }
}
  • Option 1
count = 0, variable = 7
count = 1, variable = 8
count = 2, variable = 9
  • Option 2
count = 2, variable = 9

Quiz 25: Indefinite Loop – While and Loop

Q1. The number of iterations are known in which loop?

  • for
  • while
  • loop

Q2. In a loop that has no terminating condition, which of the following is true?

  • program will give an error
  • program will run indefinite times

Q3. How many times does the loop run?

fn main() {
  let mut var = 1; //define an integer variable
  let mut found = false; // define a boolean variable
  // define a while loop
  while !found {
      var=var+1;
      //print the variable
      println!("{}", var);
      // if the modulus of variable is 1 then found is equal to true
      if var % 3 == 1 {
        found = true; 
      }
      println!("Loop runs");
  }
}
  • 1
  • 2
  • 3

Quiz 26: Break Statement

Q1. How many times does the print statement in the loop run?

fn main() {
  for i in 0..10 {
    println!("i:{}", i);
    if i == 5 {
      break;
    }
  }
}
  • 5
  • 6
  • 7

Quiz 27: Continue Statement

Q1. How many times is the statement “I did not encounter continue statement” printed in the code below?

fn main() {
      let mut var = 1; 
      let mut found = false;
      while !found {
          var = var + 1;
          println!("{}", var);

          if var == 5 {
              println! ("I encoutered a continue statement");
              continue;
            }
          println!("I did not encounter continue statement");

           if var == 6 {
               found = true;
           }
        }
}
  • 4
  • 5
  • 6

Challenge 9: Find The Factorial

Answer:

fn test(n:i32) {
   let mut factorial = 1;

   if n < 0 {
      println!("0");
   }
   else if n == 0 {
      println!("1");
   }
   else
   {
      for i in 1..n + 1 {
         factorial = factorial * i
      }
      println!("{}", factorial);
   }
}

Challenge 10: Count Iterations of a Loop Until a Condition

Answer:

fn test(mut x:i32) {
    // define a mutable variable
    let mut count = 0;
    // define a while loop
    while x >= 0 {
       x = x - 3;
       count = count + 1;
    }
    println!("{}", count);
}

Challenge 11: Print a Right-Angled Triangle

Answer:

fn test(n:i32) {
    // define a nested for loop
    for i in 0..n { //outer loop
        for j in 0..i + 1 { // inner loop
            print!("{}",'&');
    }
    println!("");
    }
}

Quiz 28: Introduction to Functions

Q1.

What is the output of the following program?

fn display_message(){
    println!("Hi this is my user defined function");
}
fn main() {
    display_message();
    println!("function is called");
}
  • Hi, this is my user defined function
    • function is called
  • Hi, this is my user defined function

Quiz 29: Functions With Parameters

Q1. What is the output of the following code?

fn my_func(param1:i32, param2:i32) {
  println!("The first value passed inside function : {}",  param1);
}
fn main() {
  let value1 = 1;
  let value2 = 2;
  my_func(value1, value2);
}
  • The first value passed inside function : 1
    • The second value passed inside function : 2
  • The first value passed inside function : 1

Quiz 30: Pass by Value

Q1. What is the output of the following code?

fn swap( x:i32, y:i32 ) {
  let temp = y;
  let y = x;
  let x = temp;
  println!("x : {}, y : {}", x , y);
}
fn main() {
  let x = 10;
  let y = 9;
  swap( x, y );
  println!("x : {}, y : {}", x , y);
}
  • Option 1
x : 9, y : 10
x : 10, y : 9
  • Option 2
x : 9, y : 10
x : 9, y : 10

Quiz 31: Pass by Reference

Q1. What is the output of the following code?

fn change(x:&mut i32, y:&mut i32){
  *x = 0;
  *y = 0;
  println!("x : {}, y : {}", x , y);
}
fn main() {
  let mut x = 10;
  let mut y = 9;
  change( &mut x, &mut y );
  println!("x : {}, y : {}", x , y);
}
  • Option 1:
x : 0, y : 0
x : 0, y : 0
  • Option 2:
x : 9, y : 10
x : 0, y : 0

Quiz 32: Returning a Value From a Function

Q1. What is the output of the following code?

fn main(){
   println!("{}", get_area(2, 2));
}
fn get_area(x:i32, y:i32) -> i32 {
   x  *  y
}
  • Option 1
4
  • Option 2
4.0

Challenge 12: Check Divisibility by 3 and 4

Answer:

fn test_divisibility_by_3_4(a:i32)->i32{
    //check if number is divisible by 3 and 4 
    if a % 3 == 0 && a % 4 == 0{
        0
    }
    //check if number is divisible by 3 and not by 4 
    else if a % 3 == 0 && a % 4 != 0 {
        1
    }
    //check if number is divisible not by 3 but 4 
    else if a % 3 != 0 && a % 4 == 0 {
        2
    }
    //check if neither divisible by 3 nor 4
    else {
        -1
    }
}

Challenge 13: Return an Array of Squares

Answer:

fn arr_square() -> [i32;5] {
    let mut square:[i32;5] = [1, 2, 3, 4, 5]; // mutable array 
    for i in 0..5 {  // compute the square of each element
        square[i] = square[i] * square[i];
    }
    square
}

Challenge 14: Find nth Fibonacci Number

Answer:

fn fibonacci(term: i32) -> i32 {
    match term {
        0 =>  0,
        1 =>  1,
        _ => fibonacci(term-1) + fibonacci(term-2),
    }
}

Quiz 33: Core Methods of String Objects

Q1. Common method of string object and string literal are:

  • len()
  • trim()
  • split()
  • split_whitespace()

Q2. Trim method is used to remove inline spaces.

  • True
  • False

Quiz 34: Iterating Over Strings

Q1. What is the output of the following code?

fn main() {
    // define a String object
    let str = String::from("Educative, course on, Rust; Programming");  
    // split on token
    for token in str.split(";") {
        println!("{}", token);
    }
}
  • Educative, course on, Rust
    • Programming
  • Educative
    • course on
    • Rust
    • Programming

Quiz 35: Updating a String

Q1. Which of the following methods cannot be used for concatenating a string with another string?

  • + operator
  • Format macro
  • push_str
  • push

Q2. What is the output of the following code?

fn main() {
  let mut s = String::from("Learn ");
  s.push('P');
  s.push_str ("rogramming");
  println!("{}!", s);
  let res= format!("{}{}",s," in Rust");
  println!("{}!", res);
}
  • Learn Programming!
    • Learn Programming in Rust!
  • Learn Programming in Rust!

Q3. What is the output of the following code?

fn main() {
  let mut s = "Learn ";
  s.push( 'P' );
  s.push_str("rogramming");
  println!("{}!", s);
  let res = format!("{}{}", s, " in Rust");
  println!("{}!", res);
}
  • Learn Programming!
    • Learn Programming in Rust!
  • Syntax error

Quiz 36: Slicing a String

Q1. What is the output of the following code?

fn main() {
   let string = "Rust Programming".to_string();
   let slice = &string[0..3]; 
   println!("{}", slice);
}
  • Rust
  • Rus

Challenge 15: Concatenate Words Starting With ‘c’

Answer:

fn test(my_str:String)-> String {
    let mut my_updated_string = "".to_string(); 
    for i in my_str.split(" "){
         if i.starts_with("c"){
             my_updated_string.push_str(i);
             my_updated_string.push(' ');
         }
        }
    my_updated_string.pop();
    my_updated_string
}

Quiz 37: Introduction to Vectors

Q1. Vectors are resizable arrays.

  • True
  • False

Q2. What is the output of the following code?

fn main() {
let my_vec = vec![1, 2, 3, 4, 5];
match my_vec.get(10) {
    Some(x) => println!("Value at given index:{}", x),
    None => println!("Sorry, you are accessing a value out of bound")
}
match my_vec.get(3) {
    Some(x) => println!("Value at given index:{}", x),
    None => println!("Sorry, you are accessing a value out of bound")
}
  
}
  • Sorry, you are accessing a value out of bound
    • Value at given index: 4
  • Value at given index: 4
    • Sorry, you are accessing a value out of bound

Quiz 38: Resizing a Vector

Q1. What is the output of the following code?

fn main() {
  
   let mut my_vec = vec![1, 2, 3, 4, 5];
   println!("Vector : {:?}",my_vec);
   println!("Length of the vector : {}",my_vec.len());
   my_vec.push(8);
   my_vec.push(7);
   my_vec.remove(2);
   my_vec.remove(1); 
   //print vector
   println!("Vector : {:?}",my_vec);
   //print the length of vector
   println!("Length of the vector : {}",my_vec.len());
}
  • Vector : [1, 2, 3, 4, 5]
    • Length of the vector : 5
    • Vector : [1, 4, 5, 8, 7]
    • Length of the vector : 5
  • Vector : [1, 2, 3, 4, 5]
    • Length of the vector : 5
    • Vector : [1, 4, 5, 7, 8]
    • Length of the vector : 5

Quiz 39: Iterating Over a Vector

Q1. What is the output of the following code?

fn main() {
   let mut my_vec = vec![1, 2, 3, 4, 5];
   for x in my_vec.iter_mut(){
       *x += 4;
   }
   my_vec.push(23); 
   println!("Vector : {:?}",my_vec);
   println!("Length of the vector : {}",my_vec.len());
}
  • Vector : [5, 6, 7, 8, 9, 23]
    • Length of the vector : 5
  • Vector : [5, 6, 7, 8, 9, 23]
    • Length of the vector : 6

Quiz 40: Slicing a Vector

Q1. What is the output of the following code?

fn main() {
   let my_vec = vec![1, 2, 3, 4, 5];
   let slice:&[i32] = &my_vec[2..6];
   println!("Slice of the vector : {:?}",slice);
}
  • Slice of the vector : [3, 4, 5]
  • Run time error

Q2. What is the output of the following code?

fn main() {
   let my_vec = vec![2, 3, 9, 8,7];
   let slice:&[i32] = &my_vec[2..4];
   println!("Slice of the vector : {:?}", slice);
}
  • Slice of the vector : [3, 9]
  • Slice of the vector : [9, 8]

Challenge 16: Resizing a Vector

Answer:

fn test(my_vec: &mut Vec<u32>)-> &mut Vec<u32>{
   let middle = (my_vec.len())/2;
   my_vec.pop(); 
   my_vec.remove(middle - 1);
   let mut sum : u32 = 0;
   for v in my_vec.iter()
   {
      sum = sum + v;
   }
   my_vec.push(sum);
   my_vec
}

Quiz 41: Introduction to Structs

Q1. The values of struct can be accessed through a:

  • . dot operator
  • [] subscript notation

Q2. The name of the struct should be in which case to avoid compiler warning?

  • PascalCase
  • snake_case

Quiz 42: Methods of Structs

Q1. Which code block has the method enclosed in it?

  • impl
  • fn

Challenge 17: Calculate Distance Between Two Points

Answer:

struct Point {
	x: i32,
	y: i32
}
fn test(point1: Point, point2: Point)-> f32 {
    let distance = i32::pow(point1.x - point2.x,2) + i32::pow(point1.y - point2.y,2);
    let a = distance as f32;
    a.sqrt()
}

Quiz 43: Introduction to Enums

Q1. Suppose you have defined an enum

enum Move{
  Left, Right, Top, Bottom
}

How would you call variant Left in the main function?

  • let my_move=Move::Left;
  • let my_move=Move:Left;

Quiz 44: Methods of Enums

Q1. What is the output of the following code?

#![allow(dead_code)]
#[derive(Debug)]
enum TrafficSignal {
  Red, Green, Yellow
}
impl TrafficSignal{
   fn is_stop(&self)->bool{
     match self{
       &TrafficSignal::Red=>return true,
       _=>return false
     }
   }
}
fn main(){
  let action = TrafficSignal::Yellow;
  println!("What is the signal value? - {:?}", action);
  println!("Do we have to stop at signal? - {}", action.is_stop());
}
  • What is the signal value? – Yellow
    • Do we have to stop at signal? – false
  • What is the signal value? – Red
    • Do we have to stop at signal? – true

Challenge 18: Find If the Day Is a Weekend

Answer:

#![allow(dead_code)]
#[derive(Debug)]
// declare an enum
enum Days {
  Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
}
//implement Days methods
impl Days{
  // if the day is a weekend
   fn is_weekend(&self)->i32{
     match self{
       &Days::Saturday=>return 1,
       &Days::Sunday=>return 1,
       _=>return 0
     }
   }
}

Quiz 45: Traits

Q1. Which of the following trait method allows you to write body of the method?

  • abstract
  • concrete

Q2. Traits are like interfaces in other object oriented languages.

  • True
  • False

Quiz 46: Generics

Q1. Which of the following types are not allowed to be made generic in Rust!

  • vectors
  • arrays
  • structs
  • enums

Challenge 19: Check If the Person Has a Driving License

Answer:

#![allow(dead_code)] 
//declare a structure
struct Car {
   owner_age:i32,
}
struct Motorbike {
   owner_age:i32,
}
//declare a trait
trait Drive {
   fn can_drive(&self)->i32;
}
//implement the trait
impl Drive for Car{
   fn can_drive(&self)->i32{
      if self.owner_age >= 18 {
         1
      }
      else {
         0
      }
   }
}
impl Drive for Motorbike{
   fn can_drive(&self)->i32{
      if self.owner_age >= 14{
         1
      }
      else {
         0
      }
   }
}

Quiz 47: Controlling Visibility Within the Same File Using ‘pub’

Q1. How can you make a call to the function inside module r?

mod r {
  pub fn print_statement() {
    println!("Hi, this a function of module r");
  }
}
  • Option 1
r :: print_statement()
  • Option 2
print_statement()

Q2. You can invoke a private function directly.

  • True
  • False

Q3. You can invoke a private function through a public function.

  • True
  • False

Q4. How can you access a function within the module containing it?

  • Using self::function_name( )
  • Using function_name( )
  • Using super :: function_name( )

Q5. How can you access a parent module’s private function from a child module’s function?

  • Using super :: function_name_parent()
  • Using self :: function_name_parent()
  • Using function_name_parent()

Q6. Suppose a function is defined outside of a module. How would you invoke it through a module?

  • super :: function_name()
  • self:: function_name()

Quiz 48: Control Visibility Within Different Files Using ‘pub’

Q1. Implicit declaration of a module in a different file makes them public by default.

  • True
  • False

Q2. For explicitly defining a module in a different file, and accessing it in a different file, make it?

  • public using pub
  • private

Quiz 49: The ‘use’ Keyword

Q1. You can only nest the modules upto three levels.

  • True
  • False

Q2. The enum is declared

enum Gender {
    Male, Female
}

How would you use the glob operator ?

  • Option 1
use Gender :: *
  • Option 2
Gender :: *

Q3. What is the output of the following code?

pub mod chapter {
    pub mod lesson {
        pub fn summary(){
            println!("This is the summary"); 
        } 
        pub mod heading { 
            pub fn illustration() {  
              println!("Hi, I'm a 3rd level nested function");
            }
        }
    }
}
use chapter::lesson::heading;
use chapter::lesson;

fn main() {
    lesson::summary();
    heading::illustration(); 
}
  • Option 1
This is the summary
Hi, I'm a 3rd level nested function
  • Option 2
Hi, I'm a 3rd level nested function

Challenge 20: Find the Area of a Triangle

Answer:

fn my_area(base: i32 , height: i32 )-> f32{ // root function
   ( base as f32 ) * ( height as f32 ) * 0.5 // compute area of triangle
}
// declare a module
mod shapes {
  // function within outer module
  pub fn triangle_area(x : i32 , y : i32) {
   println!("{}", super :: my_area ( x , y )); // invoke the root function
  }
}

Quiz 50: Memory Management

Q1. Primitive variables ae stored on:

  • Stack
  • Heap

Q2. Non-primitive variables are stored on:

  • Stack
  • Heap

Q3. Which of the following allows unknown data size storage?

  • Stack
  • Heap

Q4. The known data size is stored on:

  • Stack
  • Heap

Quiz 51: Copy Type and Moved Type

Q1. Which of the following are copied types?

  • Array
  • f32
  • i32
  • Vector

Q2. Which of the following are moved types?

  • Array
  • i32
  • String
  • Vector

Quiz 52: Borrowing

Q1. Can a variable have a shared borrow and a mutable borrow reference within the same scope?

  • Yes
  • No

Q2. Why does this code give an error?

fn main() {
  let a = String::from("Rust"); 
  let b = a;
  let c = &b;
  println!("println!{}", a);
}
  • Trying to print moved value a
  • c borrows b

Q3. Why does this code give an error?

fn main() {
  let a = String::from("Rust"); 
  let b = a;
  let c = &a;
}
  • Variable c is making an invalid access
  • Variable a is out of scope

Rust Exam

Q1. Which of the following is the correct way of printing the variable language?

  • println(“{}”, language);
  • println(language);
  • println!(“{}”, language);
  • println!(language);

Q2. Which of the following statement correctly updates the variable value?

  • fruit = “apple”; fruit = “orange”;
  • let fruit = “apple”; fruit = “orange”;
  • let mut fruit = “apple”; fruit = “orange”;
  • let fruit:&str = “apple”; fruit = “orange”;

Q3. What is the output of the following code?

fn main(){
     let a  = 3;
     println!("{}", !a);
}
  • -3
  • -4
  • 3
  • 4

Q4. What will be the output of the below Rust code?

fn main() {
   const L:i32 = 1; 
   println!("{}", L << 1 & 1);
}
  • 1
  • 0
  • -1
  • 2

Q5. Three operand abc are assigned a value 7.

fn main(){
 let a = 7;
 let b = 7;
 let c = 7;
}

We want to apply a bitwise operation such that the output is same.

a Operator b Operator c  

Note that the same bitwise operator is used in the entire expression, i.e., if we use AND, we will say a & b & c.

Keeping the above in mind, your task is to determine which of the following bitwise operators when used in expression will result in the same output?

  • AND, OR, NOT
  • AND, OR, XOR
  • AND, Left shift by 1,XOR
  • XOR, OR, Right shift by 2

Q6. What is the output of the following code?

fn main() {  
    let course = ("programming", "beginner");
    if let ("gamming", c) = course {
        println!("{}", c);
    } else {
        println!("Value unmatched");
    }
}
  • beginner
  • programming
  • Values unmatched
  • Error

Q7. What is the output of the following code?

fn main() {
   if (1 < 0) && (0 < -1) {
      println!("Pass");
   }
   else if (1 > 0) | false {
      println!("Fail");
   }
   else{
      println!("Educative");
   }
}
  • Educative
  • Fail
  • Pass
  • Error

Q8. Trace the output of the following program.

fn main() {
  let mut i = 1;
  loop {
    print!("{}", i);
    if i == 5 {
      break;
    }
    i = i + 1;    
  }
}
  • 12345
  • 1234
  • Error
  • None of the above

Q9. Trace the output of the following program

fn main() {
  for i in 0..5 {
     if i == 2 {
       continue;
      }
      print!("{}", i);
  }
}
  • 01234
  • 0134
  • 012345
  • 01345

Q10. What makes main a special function?

  • It is the entry point to the program
  • It has a specific signature
  • It has no specific signature; it can take parameters just like an ordinary function
  • Both A & B

Q11. Trace the output of the following program

fn modulus(x: i32, y: i32) -> i32 {
    x % y
}

fn main() {
    println!("{}", modulus(10 + 2, 5 + 3));
}
  • 4
  • 0
  • 2
  • 1

Q12. What is the output of the following program?

fn factorial(num: u64) -> u64 {
    match num {
        _ => factorial(num - 1) * num,
    }
}

fn main() {
    println!("{} ", factorial(4));
}
  • 12
  • 24
  • Compile-time error
  • None of the above

Q13. Trace the output of the following program.

fn say_fruits(fruits: i32) {
    println!("{}", fruits * fruits);
}

fn main() {
    say_fruits(10);
    println!("{}", fruits);
}
  • 10 100
  • 100 10
  • 100
  • Compile-time error

Q14. What is the output of the following code?

fn main() {
    let first_name = "Max";
    let last_name = " Well";
    let full_name = first_name + last_name;
    println!("{}", full_name);
}
  • Max Well
  • Max + Well
  • “Max” “Well”
  • Compile-time error

Q15. What is the output of the code below?

fn main(){
   let course = "Rust".to_string();
   let _course_type = "Programming".to_string();
   let result = format!("{1} {0}", course, _course_type);
   println!("{}", result);
}
  • Rust Programming
  • Programming Rust
  • Compile-time error
  • Rust Rust

Q16. What is the output of the code below?

fn main() {
    let numbers = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

    println!("{:?}", &numbers[..4]);
}
  • 01234
  • 0123
  • 1234
  • 123

Q17. What is the length and capacity of the vector after the execution of the following code?

fn main() {
   let mut my_vec = vec![1, 2, 3, 4, 5];
   my_vec.pop();
   my_vec.pop(); 
   my_vec.pop();
   my_vec.push(1);
}
  • length:5 capacity:5
  • length:3 capacity:5
  • length:5 capacity:2
  • length:5 capacity:1

Q18. Trace the output of the following program

fn main() {
   let mut my_vec = vec![1, 2, 3, 4, 5];
   for x in my_vec.iter_mut(){
       *x *= 2;
   }
   my_vec.pop();
   my_vec.push(15);
   print!("{:?}", my_vec);
}
  • [2, 4, 6, 8, 10]
  • [2, 4, 6, 8, 15]
  • [2, 4, 6, 8, 10, 15]
  • [2, 4, 6, 8]

Q19. Trace the output of the following program

struct SportsItems {
    rackets: i32,
    balls: i32,
}

fn increase_sports_items(sports_items: SportsItems) -> SportsItems {
    let sports_items = SportsItems {
        rackets: sports_items.rackets * 2,
        balls: sports_items.balls * 3,
    };
    sports_items
}

fn new_sports_items() -> SportsItems {
    let sports_items = SportsItems {
        rackets: 10,
        balls: 5,
    };
    sports_items
}

fn print_sports_items(sports_items: SportsItems) {
    println!("You have {} rackets and {} ball
s", sports_items.rackets, sports_items.balls);
}

fn main() {
    let sports_items = new_sports_items();
    let sports_items = increase_sports_items(sports_items);
    print_sports_items(sports_items);
}
  • You have 0 rackets and 0 balls
  • You have 10 rackets and 5 balls
  • You have 20 rackets and 15 balls
  • Compile-time error

Q20. Trace the output of the following program.

enum Device {
    Switch,
    Router,
}

impl Device {
    fn power_level(&self) -> Option<u32> {
        match self {
            Device::Switch => None,
            Device::Router => Some(18000),

        }
    }

    fn name(&self) -> &str {
        match self {
            Device::Switch => "Switch",
            Device::Router => "Router",
        }
    }

    fn print_power(&self) {
        match self.power_level() {
            None => {
                println!("{}'s power level:", self.name(), level);
            }
            Some(level) => {
                println!("{} power level: {}", self.name(), level);
            }
        }
    }
}

fn main() {
    Device::Switch.print_power();
    Device::Router.print_power();
}
  • None 18000
  • Switch’s power level: Router power level: 18000
  • Compile-time error
  • None of the above

Q21. Trace the output of the following program

trait Float {
    fn float(&self) -> Self;
}

impl Float for i32 {
    fn float(&self) -> Self {
        self * 3
    }
}

impl Float for i64 {
    fn float(&self) -> Self {
        self * 2
    }
}

fn main() {
    println!("{}", 5_i32.float());
    println!("{}", 5_i64.float());
}
  • 10 10
  • 10 15
  • 15 15
  • 15 10

Q22. Trace the output of the following program.

pub mod chapter {
    pub mod lesson {
        pub fn summary(){
            println!("Summary"); 
        } 
        pub mod heading {  
            pub fn illustration() {  
              println!("Content visualization");
            }
        }
    }
}
use chapter::lesson::heading;
use chapter::lesson;
 
fn main() {
    lesson::summary();
    heading::illustration(); 
}
  • Summary Content visualization
  • Summary
  • Content visualization
  • Compile-time error

Q23. Trace the output of the following program

fn main() {
    let a = String::from("Rust");
    let b = a; 
    println!("a:{} , b:{}", a, b); 
}
  • a: Rust b: Rust
  • a:Rust b:
  • Compile-time error
  • None of the above

Q24. Identify the rules for lifetime elision.

  • An input lifetime is a lifetime associated with a parameter of a function.
  • An output lifetime is a lifetime associated with the return value of a function.
  • An output lifetime is a lifetime associated with the input and return value of a function.
  • Both A and B
  • None of the above

Q25. const variables are declared in global and local scope but let variables are declared in the local scope only.

  • True
  • False

Q26. Tuples are homogenous and arrays are heterogeneous data types.

  • True
  • False

Q27. A variable can be updated through a dereference operator if it’s a shared borrow.

  • True
  • False

Q28. Functions may return results of different types.

  • True
  • False

Q29. Match the operator symbol in the left column with their respective name on the right side:

  • *
  • |
  • | |
  • & mut
  • Bitwise
  • Borrowing
  • Dereferencing
  • Logical

Q30. Match the conditional statement in the left column with their respective purpose on the right column:

  • if
  • if let
  • match
  • There is a pattern in the condition and it is to be matched with the scrutinee expression
  • compare multiple possible conditions of an expression
  • test the truthiness of an expression

Q31. In this coding exercise, you are asked to write the body of a function called maximum that returns the maximum value in an array.

Below are some examples of arrays with maximum values:

ArrayMaximum value
[1, 2, 3, 4, 5]5
[2, 4, 6, 8, 10]10
[1, 3, 8, 11, 7]11

Q32. In this coding exercise, you are asked to write the body of a function called determine_isogram that returns 1 or 0 depending upon whether the given input string is an isogram or not respectively.

An isogram (a.k.a “nonpattern word”) is a word or phrase that does not have a repeating letter. However, spaces, and hyphens are allowed to appear multiple times.

The word isograms is not an isogram, because the letter ‘s’ is repeated twice.

Examples of isograms:

StringIsogram
isograms0
banana0
trace1
jackets1
background1
downstream1
six-year-old1
apple0
rose1
garden1

Q33. In this coding exercise, you are asked to write the body of a function called reverse that takes a vector, manipulates it, and returns the reversed vector.

Below are some examples of given input vector and reversed vector as output:

VectorReversed vector
[1, 2, 3, 4, 5][5, 4, 3, 2, 1]
[2, 4, 6, 8, 10][10, 8, 6, 4, 2]
[1, 3, 8, 11, 7][7, 11, 8, 3, 1]

Note: Only use the vector passed as input to the function.

Q34. In this coding exercise, you are asked to implement the trait method called fly. You are provided with a struct with a time parameter that defines time taken by species to cover x distance. You have to implement the trait to determine the distance for each specie given time.

Note: It has been observed that birds fly 10 feet per 1s, and bees can fly 2 feet per sec. The value of time is provided to you as input.

Below are some examples:

SpecieInput(seconds)Output
🐝5Bee flies 10 feet
🐦5Bird flies 50 feet
🐝8Bee flies 16 feet
🐦8Bird flies 80 feet
🐝10Bee flies 20 feet
🐦10Bird flies 100 feet

Note: You have to calculate distance and write the print statement as shown in the sample output above.

Q35. In this coding exercise, you are asked to write the body of a function called category that returns the category of the lists given as input.

There can be 4 categories:

  1. Two lists are equal
  2. List 1 is a sublist of the list 2
  3. List 1 is a super list of the list 2
  4. Two lists are unequal

An enum Comparison is declared with 4 variants EqualSublistSuperlist and Unequal.

The given input lists can belong to any of the categories. Use the function category to return the true category of the given lists.

List AList BCategory
[1, 2, 3][1, 2, 3, 4, 5]A is a Sublist of B
[1, 2, 3, 4, 5][1, 2, 3]A is a Superlist of B
[1, 2, 3][1, 2, 3]A is Equal to B
[1, 2, 3, 4, 5][1, 2, 4]A is Unequal to B

Note: You have to return the true category in the form of enum.

Conclusion:

I hope this Learn Rust from Scratch Educative Quiz Answers would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.