WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Intermediate · question 27 of 100

How do you define a generic function or struct in Rust? Provide an example.?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

In Rust, you can define a generic function or struct by specifying a type parameter with angle brackets ‘<>‘. This allows you to write code that can adapt to work with different types of data, without having to write separate functions or structs for each type.

Here is an example of how to define a generic function that swaps the values of two variables using a type parameter:

    fn swap<T>(a: &mut T, b: &mut T) {
        let temp = *a;
        *a = *b;
        *b = temp;
    }

In this function, ‘T‘ is the type parameter that specifies the type of the variables being swapped. The function takes two mutable references to values of type ‘T‘, swaps their values, and returns nothing.

Here is an example of how to use this function with two ‘i32‘ values:

    fn main() {
        let mut x = 42;
        let mut y = 24;
        println!("Before: x = {}, y = {}", x, y);
        swap(&mut x, &mut y);
        println!("After: x = {}, y = {}", x, y);
    }

The output of this program will be:

    Before: x = 42, y = 24
    After: x = 24, y = 42

You can also define generic structs using type parameters. Here is an example of a ‘Point<T>‘ struct that can store values of any type:

    struct Point<T> {
        x: T,
        y: T,
    }

Here, ‘T‘ is the type parameter that specifies the type of the ‘x‘ and ‘y‘ values stored in the ‘Point‘. This allows you to create ‘Point‘ values with different types:

    fn main() {
        let p1 = Point { x: 1, y: 2 };
        let p2 = Point { x: 3.14, y: 2.718 };
        let p3 = Point { x: "hello", y: "world" };
    }

In this example, ‘p1‘ is a ‘Point<i32>‘, ‘p2‘ is a ‘Point<f64>‘, and ‘p3‘ is a ‘Point<&str>‘.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics