Can you write a macro to invoke the default() operator in rust?

StackOverflow https://stackoverflow.com/questions/22602205

  •  19-06-2023
  •  | 
  •  

سؤال

Something like:

macro_rules! default(
  ($T:ty, $($args:expr)*) => (
    $T { $($args)*, ..Default::default() };
  );
)

...but with a magical type instead of expr, so you could do something like:

let p = default!(CItem, _z: ~"Hi2", x: 10);
let q = default!(CItem, _z, ~"Hi2", x, 10);
let r = default!(CItem, { _z: ~"Hi2", x: 10 });

Or something along those lines?

Is there any macro symbol that simply picks up a literal block of characters without first parsing it as a type/expr/etc?

(I realize you'd typically just write a CItem::new(), but this seems like a nice situation in some circumstances)

هل كانت مفيدة؟

المحلول

Macros can have multiple pattern to match the syntax, so you have to write a seperate pattern for every case seperatly like this:

macro_rules! default(
    ($t:ident, $($n:ident, $v:expr),*) => {
        $t { $($n: $v),*, ..Default::default() }
    };
    ($t:ident, $($n:ident: $v:expr),*) => {
        default!($t, $($n, $v),*)
    };
)

As you can see there are two patterns, the first matching pairs seperated by comma and the second one pairs seperated by colon.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top