简体   繁体   中英

How could I use a use a regex-like procedure on a code string with a macro in Rust?

I've written multiple functions in my code that have snippets that are duplicated three times, for red blue and green. It's getting pretty old and cluttering up my code, and I would prefer to compress them each into one snippet encapsulated in a macro. However, I can't find any information in the book about a macro that would operate like this, even though generating code is their sole purpose. Ideally, it would look something like this:

rgb_triple!("
for i in 0..(data.dimensions.width * data.dimensions.height) {
    $color_map[i] = 255;
}
")

expanding to this:

for i in 0..(data.dimensions.width * data.dimensions.height) {
    red_map[i] = 255;
}
for i in 0..(data.dimensions.width * data.dimensions.height) {
    green_map[i] = 255;
}
for i in 0..(data.dimensions.width * data.dimensions.height) {
    blue_map[i] = 255;
}

What would be the best way for me to do this (even if this isn't)?

I would write a function that takes the color_map as mutable reference. Something like:

fn do_it(color_map: &mut Vec<u32>, data: &Data) {
    for i in 0..(data.dimensions.width * data.dimensions.height) {
        color_map[i] = 255;
    }
}

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