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

Rust · Advanced · question 56 of 100

What is a const-generic parameter in Rust, and how do you use it? Provide an example.?

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

In Rust, a const-generic parameter is a parameterization technique that allows developers to use constant values as type parameters in generic code. This technique allows for more flexibility in generic programming as it enables the use of constants in the definition and implementation of generic types.

The syntax for using a const-generic parameter in Rust is as follows:

    struct MyStruct<const N: usize> {
        // fields and methods
    }

In this example, ‘MyStruct‘ is a struct with a const-generic parameter ‘N‘.

Here is an example of how to use a const-generic parameter:

    fn main() {
        let arr: [i32; 5] = [1, 2, 3, 4, 5];
        let sum = sum_of_array::<5>(arr);
        println!("{}", sum);
    }
    
    fn sum_of_array<const N: usize>(arr: [i32; N]) -> i32 {
        let mut sum = 0;
        for i in 0..N {
            sum += arr[i];
        }
        sum
    }

In this example, the ‘sum_of_array‘ function takes an array of ‘i32‘ values of length ‘N‘ specified as a const-generic parameter. The function calculates the sum of all the elements in the array and returns the value.

To call the ‘sum_of_array‘ function, we pass the argument ‘arr‘ with the length of the array as the const-generic parameter ‘<5>‘. This way, Rust knows that the function is expecting an array of length 5 and can verify that the passed-in array has the right size.

Overall, const-generic parameters are a powerful feature in Rust that allows developers to write more flexible and efficient generic code.

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