Optional function parameters using macros
- Rust does not allow the declaration of the same function-name with different signatures as many other languages.
- Rust does not allow the definition of a function with optional parameters and/or with default values.
- We can use declarative macros to overcome this limitation.
- We could define a macro "only for the case with the optional value" or, as we do in this example, we can create a macro for both cases.
examples/macros/optional-parameter/src/main.rs
// #![feature(trace_macros)] macro_rules! ping { ($address: expr) => { ping($address, 4); }; ($address: expr, $repeat: expr) => { ping($address, $repeat); }; } fn ping(address: &str, mut repeat: u8) { while repeat > 0 { println!("ping {address}"); repeat -= 1; } } fn main() { // trace_macros!(true); ping("localhost", 1); //ping("remote"); ping!("remote"); ping!("localhost", 3); // trace_macros!(false); }
ping localhost ping remote ping remote ping remote ping remote ping localhost ping localhost ping localhost