Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to access the field name of the struct Person.
Rust
struct Person {
name: String,
age: u32,
}
fn main() {
let person = Person { name: String::from("Alice"), age: 30 };
println!("Name: {}", person.[1]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the struct name instead of the field name after the dot.
Using incorrect capitalization for the field name.
✗ Incorrect
To access a field of a struct in Rust, use dot notation with the exact field name. Here,
person.name accesses the name field.2fill in blank
mediumComplete the code to access the field age of the struct Employee.
Rust
struct Employee {
id: u32,
age: u8,
}
fn main() {
let emp = Employee { id: 101, age: 45 };
println!("Employee age: {}", emp.[1]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the struct variable name instead of the field name.
Capitalizing the field name incorrectly.
✗ Incorrect
Use dot notation with the exact field name to access it. Here,
emp.age gets the age field.3fill in blank
hardFix the error in accessing the field title of the struct Book.
Rust
struct Book {
title: String,
pages: u32,
}
fn main() {
let book = Book { title: String::from("Rust Guide"), pages: 250 };
println!("Book title: {}", book.[1]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using capitalized field name
Title instead of title.Trying to access the struct variable instead of a field.
✗ Incorrect
Field names are case sensitive. The correct field is
title in lowercase, so use book.title.4fill in blank
hardFill both blanks to create a struct Car and access its model field.
Rust
struct [1] { model: String, year: u16, } fn main() { let my_car = [2] { model: String::from("Tesla"), year: 2022 }; println!("Car model: {}", my_car.model); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names or different capitalization for the struct and instance.
Using a variable name instead of the struct name in the declaration.
✗ Incorrect
The struct name must be the same when declared and when creating an instance. Both blanks should be
Car.5fill in blank
hardFill all three blanks to define a struct Point, create an instance, and access the x field.
Rust
struct [1] { x: i32, y: i32, } fn main() { let p = [2] { x: 10, y: 20 }; println!("X coordinate: {}", p.[3]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names or capitalization for the struct and instance.
Accessing a field that does not exist or misspelling the field name.
✗ Incorrect
The struct name is
Point, the instance is created with Point, and the field accessed is x.