Challenge - 5 Problems
Rust Struct Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Rust code creating a struct instance?
Consider the following Rust code that defines a struct and creates an instance. What will be printed when running this code?
Rust
struct Book {
title: String,
pages: u32,
}
fn main() {
let my_book = Book {
title: String::from("Rust Basics"),
pages: 250,
};
println!("{} has {} pages", my_book.title, my_book.pages);
}Attempts:
2 left
💡 Hint
Look at how the struct fields are accessed and printed with println! macro.
✗ Incorrect
The struct instance 'my_book' has fields 'title' and 'pages'. The println! macro prints them in the order given, so the output is 'Rust Basics has 250 pages'.
❓ Predict Output
intermediateWhat error occurs when creating a struct instance with missing fields?
Given this Rust struct and code, what error will the compiler produce?
Rust
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point {
x: 10,
};
}Attempts:
2 left
💡 Hint
Rust requires all fields to be initialized unless using struct update syntax.
✗ Incorrect
The struct Point has two fields, x and y. Omitting y causes a compiler error about the missing field.
🔧 Debug
advancedWhy does this Rust code fail to compile when creating a struct instance?
Examine the code below. Why does it fail to compile?
Rust
struct User {
username: String,
active: bool,
}
fn main() {
let user1 = User {
username: "alice",
active: true,
};
}Attempts:
2 left
💡 Hint
Check the type of the value assigned to the username field.
✗ Incorrect
The username field expects a String, but a string slice (&str) is given. Rust requires explicit conversion using String::from or .to_string().
🧠 Conceptual
advancedWhat does the struct update syntax do in Rust?
Given a struct instance, what is the effect of using the update syntax `..` when creating a new instance?
Rust
struct Config {
debug: bool,
verbose: bool,
}
fn main() {
let default = Config { debug: false, verbose: false };
let custom = Config { debug: true, ..default };
}Attempts:
2 left
💡 Hint
Think about how the `..` syntax helps avoid repeating field values.
✗ Incorrect
The update syntax copies remaining fields from the given instance, allowing you to override only some fields.
❓ Predict Output
expertWhat is the output of this Rust code using tuple structs?
Consider the tuple struct and code below. What will be printed?
Rust
struct Color(u8, u8, u8);
fn main() {
let black = Color(0, 0, 0);
let white = Color(255, 255, 255);
println!("Black: ({}, {}, {}), White: ({}, {}, {})", black.0, black.1, black.2, white.0, white.1, white.2);
}Attempts:
2 left
💡 Hint
Tuple struct fields are accessed by dot and index number starting at 0.
✗ Incorrect
Tuple structs use numbered fields starting at 0. Accessing black.0, black.1, black.2 prints the three values correctly.
