Rust Struct Quiz

Rust
0 Passed
0% acceptance

40 comprehensive questions on Rust's struct system, covering named fields, tuple structs, methods, associated functions, and field ownership — with 11 code examples demonstrating practical struct usage.

40 Questions
~80 minutes
1

Question 1

What is a struct in Rust and why are they useful?

A
A custom data type that groups related values together, allowing you to name and package related data for clarity and reuse
B
A way to define functions
C
A replacement for arrays
D
A way to define constants
2

Question 2

How do you define a struct with named fields in Rust?

A
struct StructName { field1: Type1, field2: Type2 }
B
struct StructName(field1: Type1, field2: Type2)
C
struct StructName = { field1: Type1, field2: Type2 }
D
struct StructName [field1: Type1, field2: Type2]
3

Question 3

How do you create an instance of a struct?

A
StructName { field1: value1, field2: value2 }
B
new StructName(field1, field2)
C
StructName(field1, field2)
D
StructName::new(field1, field2)
4

Question 4

What will this struct definition and instantiation create?

rust
struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

fn main() {
    let user1 = User {
        email: String::from("[email protected]"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    };
}
A
A User struct instance with all fields initialized in a different order than defined
B
Compilation error due to field order mismatch
C
A User struct with default values for missing fields
D
Runtime error
5

Question 5

How do you access fields of a struct instance?

A
Using dot notation: instance.field_name
B
Using bracket notation: instance[field_name]
C
Using arrow notation: instance->field_name
D
Fields cannot be accessed directly
6

Question 6

What is a tuple struct and how does it differ from a regular struct?

A
A struct with unnamed fields accessed by index, useful when field names aren't important
B
A struct that can be used as a tuple
C
A tuple that can be used as a struct
D
There is no difference
7

Question 7

How do you define a tuple struct?

A
struct StructName(Type1, Type2, Type3);
B
struct StructName { field1: Type1, field2: Type2 };
C
struct StructName = (Type1, Type2);
D
struct StructName [Type1, Type2];
8

Question 8

How do you access fields of a tuple struct?

A
Using dot notation with indices: instance.0, instance.1
B
Using bracket notation: instance[0], instance[1]
C
Using field names: instance.field1
D
Tuple struct fields cannot be accessed
9

Question 9

What will this tuple struct code output?

rust
struct Color(i32, i32, i32);

fn main() {
    let black = Color(0, 0, 0);
    println!("Black color: ({}, {}, {})", black.0, black.1, black.2);
}
A
Black color: (0, 0, 0)
B
Compilation error
C
Black color: (0, 0, 0
D
Runtime error
10

Question 10

How do you implement methods on a struct?

A
Use impl StructName { fn method_name(&self) { ... } }
B
Use struct StructName { fn method_name(&self) { ... } }
C
Methods cannot be implemented on structs
D
Use class StructName { fn method_name(&self) { ... } }
11

Question 11

What is the difference between &self, &mut self, and self in method parameters?

A
&self borrows immutably, &mut self borrows mutably, self takes ownership
B
&self takes ownership, &mut self borrows immutably
C
They are all the same
D
self parameters are not allowed
12

Question 12

What will this method implementation do?

rust
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect = Rectangle { width: 30, height: 50 };
    println!("Area: {}", rect.area());
}
A
Print 'Area: 1500' by calculating width * height
B
Compilation error
C
Print 'Area: 0'
D
Runtime error
13

Question 13

How do you implement associated functions (static methods) on a struct?

A
Use impl StructName { fn function_name() -> Self { ... } } without self parameter
B
Use static fn in the struct definition
C
Associated functions cannot be implemented
D
Use class methods syntax
14

Question 14

What is a common use case for associated functions?

A
Creating constructor functions like StructName::new()
B
Accessing instance fields
C
Modifying instance data
D
Associated functions have no common use cases
15

Question 15

What will this associated function implementation create?

rust
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn square(size: u32) -> Rectangle {
        Rectangle { width: size, height: size }
    }
}

fn main() {
    let sq = Rectangle::square(3);
    println!("Square: {}x{}", sq.width, sq.height);
}
A
A Rectangle instance with width and height both set to 3
B
Compilation error
C
A Rectangle with default values
D
Runtime error
16

Question 16

How does field ownership work in structs when the struct is moved?

A
When a struct is moved, ownership of all its fields is transferred
B
Fields retain their original ownership
C
Fields are automatically cloned
D
Fields become invalid
17

Question 17

What happens when you try to access a field of a moved struct?

A
Compilation error: value borrowed here after move
B
The field is still accessible
C
Runtime error
D
The field gets a default value
18

Question 18

How do you modify struct fields when the struct is mutable?

A
Declare the instance as mut and assign to fields: mut_instance.field = new_value
B
Use setter methods
C
Fields cannot be modified
D
Use the mut keyword on individual fields
19

Question 19

What will this mutable struct code do?

rust
struct User {
    email: String,
    username: String,
    active: bool,
}

fn main() {
    let mut user1 = User {
        email: String::from("[email protected]"),
        username: String::from("someusername123"),
        active: true,
    };
    user1.email = String::from("[email protected]");
    println!("New email: {}", user1.email);
}
A
Print 'New email: [email protected]'
B
Compilation error
C
Print the original email
D
Runtime error
20

Question 20

How do you create a struct with some fields from another struct instance?

A
Use struct update syntax: StructName { field: value, ..existing_instance }
B
Copy the struct and modify fields
C
Use inheritance
D
This is not possible
21

Question 21

What will this struct update syntax create?

rust
struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

fn main() {
    let user1 = User {
        email: String::from("[email protected]"),
        username: String::from("someusername123"),
        active: true,
        sign_in_count: 1,
    };
    let user2 = User {
        email: String::from("[email protected]"),
        ..user1
    };
    println!("User2 active: {}", user2.active);
}
A
Print 'User2 active: true' with other fields copied from user1
B
Compilation error
C
Print 'User2 active: false'
D
Runtime error
22

Question 22

How do you destructure a struct in a let binding?

A
Use let StructName { field1, field2 } = instance;
B
Use let (field1, field2) = instance;
C
Use let [field1, field2] = instance;
D
Structs cannot be destructured
23

Question 23

What will this struct destructuring do?

rust
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 0, y: 7 };
    let Point { x, y } = p;
    println!("x: {}, y: {}", x, y);
}
A
Print 'x: 0, y: 7' by extracting fields into variables
B
Compilation error
C
Print 'x: 0, y: 0'
D
Runtime error
24

Question 24

How do you implement the Debug trait for a struct to enable println! formatting?

A
Use #[derive(Debug)] above the struct definition
B
Implement Debug manually with fmt method
C
Both A and B are valid
D
Debug cannot be implemented for structs
25

Question 25

What is the difference between tuple structs and regular structs?

A
Tuple structs have unnamed fields, regular structs have named fields
B
Tuple structs are immutable, regular structs are mutable
C
Tuple structs use less memory
D
There is no functional difference
26

Question 26

When should you use tuple structs instead of named field structs?

A
When you want to give a tuple a specific name but don't need named fields
B
When performance is critical
C
When you need inheritance
D
Tuple structs should never be used
27

Question 27

How do you handle structs with many fields in function parameters?

A
Pass references &StructName to avoid moving large structs
B
Pass by value since structs are small
C
Use global variables
D
Split the struct into smaller structs
28

Question 28

What is the unit-like struct and when is it useful?

A
A struct with no fields: struct UnitStruct; useful for implementing traits on types
B
A struct with one field
C
A struct that behaves like a unit type
D
Unit-like structs are not useful
29

Question 29

How do you implement the Display trait for custom formatting?

A
Implement fmt method in impl Display for StructName block
B
Use #[derive(Display)]
C
Display is automatically implemented
D
Use println! formatting
30

Question 30

What will this Display implementation do?

rust
use std::fmt;

struct Point {
    x: i32,
    y: i32,
}

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

fn main() {
    let p = Point { x: 3, y: 4 };
    println!("{}", p);
}
A
Print '(3, 4)' using the custom Display implementation
B
Compilation error
C
Print the debug representation
D
Runtime error
31

Question 31

How do you create methods that modify struct fields?

A
Use &mut self parameter to borrow mutably and modify fields
B
Use &self and return a new instance
C
Methods cannot modify fields
D
Use self parameter to take ownership
32

Question 32

What is the difference between methods and associated functions?

A
Methods take self parameter and operate on instances, associated functions don't take self and are called on the type
B
Associated functions take self, methods don't
C
They are identical
D
Methods are static, associated functions are instance methods
33

Question 33

How do you implement getter and setter methods for struct fields?

A
Getters return &field, setters take &mut self and new_value parameter
B
Use automatic getter/setter generation
C
Getters and setters are not idiomatic in Rust
D
Use public fields instead
34

Question 34

What happens to struct field ownership when implementing Drop trait?

A
Drop implementation controls cleanup of owned fields when the struct goes out of scope
B
Fields are automatically cleaned up
C
Drop has no effect on field ownership
D
Fields lose their ownership
35

Question 35

How do you handle structs containing references?

A
Use lifetimes to ensure referenced data outlives the struct
B
References cannot be stored in structs
C
Use Rc for reference counting
D
Use raw pointers
36

Question 36

What is struct field visibility and how does it work?

A
Fields are private by default, can be made public with pub keyword
B
All fields are public by default
C
Fields inherit struct visibility
D
Field visibility cannot be controlled
37

Question 37

How do you create a struct with borrowed fields?

A
struct StructName<'a> { field: &'a Type } using lifetime parameters
B
struct StructName { field: &Type }
C
Borrowed fields are not allowed
D
Use Rc<Type> for borrowed data
38

Question 38

What is the builder pattern and how is it implemented with structs?

A
A pattern using method chaining to construct complex structs, with each method returning Self
B
A pattern using inheritance for struct construction
C
A pattern using macros for struct creation
D
The builder pattern is not used in Rust
39

Question 39

How do you implement Clone trait for a struct?

A
Use #[derive(Clone)] for automatic implementation or manual impl Clone
B
Clone is automatically implemented
C
Use copy() method
D
Clone cannot be implemented for structs
40

Question 40

In a complex application managing user profiles with multiple optional fields, how would you design the user struct to handle missing data gracefully?

A
Use Option<T> for optional fields: struct User { name: String, email: Option<String>, phone: Option<String> }
B
Use nullable types or default values
C
Use separate structs for different user types
D
Use a HashMap for all user data

QUIZZES IN Rust