简体   繁体   English

我如何在 Rust 中使用带有宏的代码字符串上使用类似正则表达式的过程?

[英]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.我会编写一个将 color_map 作为可变引用的函数。 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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