简体   繁体   中英

How to split an ident into letters in Rust macro?

I need to write an multiply macro which converts ident into single letter idents and multiply them.

let a = 4;
let b = 7;
println!("{}", multiply!(abbabbb));
// println!("{}", (a * b * b * a * b * b * b))

but I dont know how to match a single letter.

I want to do something like this:

macro_rules! multiply {
    ($id:letter$other:tt) => {
        $id * multiply!($other)
    };
    ($id:ident) => {
        $id
    }
}

You can't do it in pattern-matching macros (as in your example), only in procedural macros.

Even in procedural macros solving your problem will be quite hacky. In Rust an indent is a single indivisible element of AST, so to convert one indent to many you'll first have to convert it to String , divide it into characters and convert the characters back to indents.

You can't do it in a macro_rules macro. The closest you can do is to add spaces between the idents:

macro_rules! multiply {
    ($($id:ident)*) => {
       1 $(* $id)*
    }
}

fn main() {
    let a = 4;
    let b = 7;
    println!("{}", multiply!(a b b a b b b));
}

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM