8.15 Variadic Functions and Macros

Rust does not support variadic functions in the same way C does, but you can use macros or work with C functions in unsafe blocks.

8.15.1 Variadic Functions in C

C Code:

#include <stdio.h>
#include <stdarg.h>

void print_numbers(int count, ...) {
    va_list args;
    va_start(args, count);
    for(int i = 0; i < count; i++) {
        int number = va_arg(args, int);
        printf("%d ", number);
    }
    va_end(args);
    printf("\n");
}

int main() {
    print_numbers(3, 10, 20, 30);
    return 0;
}

8.15.2 Rust Equivalent Using Macros

Rust macros can accept a variable number of arguments.

macro_rules! print_numbers {
    ($($x:expr),*) => {
        $(
            print!("{} ", $x);
        )*
        println!();
    };
}
fn main() {
    print_numbers!(10, 20, 30);
}
  • Macros are a powerful feature in Rust that allow for metaprogramming.