0
0
Rustprogramming~10 mins

Generic functions in Rust - Interactive Code Practice

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

Complete the code to declare a generic function that returns the input value.

Rust
fn identity<T>(value: T) -> T {
    return [1];
}
Drag options to blanks, or click blank then click option'
Areturn
BT
Cidentity
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the type name instead of the parameter.
Using the function name instead of the parameter.
2fill in blank
medium

Complete the code to call the generic function with an integer argument.

Rust
fn main() {
    let result = identity::<[1]>(5);
    println!("{}", result);
}
Drag options to blanks, or click blank then click option'
Ai32
Bf64
CString
Dbool
Attempts:
3 left
💡 Hint
Common Mistakes
Using a floating-point type like f64 for an integer argument.
Using a non-numeric type like String.
3fill in blank
hard

Fix the error in the generic function declaration by completing the missing syntax.

Rust
fn [1]<T>(x: T) -> T {
    x
}
Drag options to blanks, or click blank then click option'
Aidentity
Bgeneric
Cprint
Dmain
Attempts:
3 left
💡 Hint
Common Mistakes
Using main which is reserved for the program entry point.
Using unrelated names like print.
4fill in blank
hard

Fill both blanks to define a generic function that swaps two values and returns a tuple.

Rust
fn swap<T>(a: T, b: T) -> ([1], [2]) {
    (b, a)
}
Drag options to blanks, or click blank then click option'
AT
Bi32
Cf64
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using different types for the tuple elements.
Using concrete types like i32 or String.
5fill in blank
hard

Fill all three blanks to complete a generic function that compares two values and returns the greater one.

Rust
fn max_value<T: PartialOrd>(a: T, b: T) -> [1] {
    if a [2] b {
        [3]
    } else {
        b
    }
}
Drag options to blanks, or click blank then click option'
AT
B>
Ca
Dbool
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a boolean instead of a value.
Using the wrong comparison operator.
Returning the wrong variable.