vendredi 3 janvier 2020

Rust: Can cfg!() contexts be aware of [#cfg()]-scoped modules

Is there a way to get cfg!() to conditionally call a function in a module that's only defined when the expression in cfg!() is true?

For example, here's an attempt to use a test-only deterministic replacement for ThreadRng.fill_bytes():

use rand::RngCore;
fn main() {
    let mut dst = [0u8, 0, 0, 0];
    if cfg!(test) {
        test::fill_bytes(&mut dst);
    } else {
        rand::thread_rng().fill_bytes(&mut dst);
    }
}

#[cfg(test)]
mod tests {
    pub fn fill_bytes(dst: &mut [u8]) {
        for i in dst.iter() {
            *i = 1;
        }
    }
}

And the error:

error[E0433]: failed to resolve: use of undeclared type or module `test`
 --> src/main.rs:5:9
  |
5 |         test::fill_bytes(&mut dst);
  |         ^^^^ use of undeclared type or module `test`

I had expected the compiler to do a pass that includes [#cfg(test)] calls first, so it would know that test::fill_bytes() was defined, and then do a pass that evaluates cfg!(). But apparently not?

Aucun commentaire:

Enregistrer un commentaire