0
0
Rustprogramming~10 mins

Why generics are needed in Rust - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Ai32
BT
CString
Dbool
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.
2fill in blank
medium

Complete 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'
AV
BPoint
CU
DT
Attempts:
3 left
💡 Hint
Common Mistakes
Using a name that does not match the field types.
Not declaring the generic type in angle brackets.
3fill in blank
hard

Fix 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'
AT
Bi32
C&str
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using a concrete type instead of a generic type.
Not declaring the generic type parameter.
4fill in blank
hard

Fill 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'
AT
BU
CV
DW
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type names inconsistently.
Not adding the trait bound : PartialOrd.
5fill in blank
hard

Fill 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'
AT
BU
CV
DW
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.