Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a function that returns the first element of a slice.
Rust
fn first_element(slice: &[[1]]) -> &[1] { &slice[0] }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a specific type like i32 limits the function to only that type.
Forgetting to use a generic type causes the function to be less flexible.
✗ Incorrect
Using T as a generic type allows the function to work with any type of slice.
2fill in blank
mediumComplete the code to declare a generic struct named Point.
Rust
struct Point<[1]> {
x: T,
y: T,
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a name that does not match the field types.
Not declaring the generic type in angle brackets.
✗ Incorrect
The generic type T allows the struct to hold any type for its fields.
3fill in blank
hardFix the error in the function signature to make it generic.
Rust
fn print_value(value: [1]) { println!("{}", value); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a concrete type instead of a generic type.
Not declaring the generic type parameter.
✗ Incorrect
Using T as a generic type requires declaring it in the function signature with <T>.
4fill in blank
hardFill both blanks to define a generic function that returns the larger of two values.
Rust
fn max_value<[1]: PartialOrd>(a: [1], b: [1]) -> [1] { if a > b { a } else { b } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type names inconsistently.
Not adding the trait bound
: PartialOrd.✗ Incorrect
The generic type T is used consistently and constrained by PartialOrd to allow comparison.
5fill in blank
hardFill all three blanks to implement a generic struct with two different types.
Rust
struct Pair<[1], [2]> { first: [1], second: [2], }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same generic type for both fields when different types are needed.
Not declaring both generic types in the struct definition.
✗ Incorrect
The struct uses two generic types T and U for its fields.