Rust `#[cfg(test)]` annotation

Viewed 126

cargo build succeed for the following code:

#[cfg(test)]
mod tests {
    #[test]
    fn func() { 
        let x = 1;
        sss
    }
}

cargo build fail for the following code:

#[cfg(test)]
mod tests {
    #[test]
    fn func() {
        sss
        let x = 1;
    }
}

https://doc.rust-lang.org/book/ch11-03-test-organization.html?highlight=%23%5Bcfg(test)%5D#the-tests-module-and-cfgtest

The #[cfg(test)] annotation on the tests module tells Rust to compile and run the test code only when you run cargo test, not when you run cargo build.

So why rustc still compiles mod tests that is annotated with #[cfg(test)] ?

1 Answers

Code that is not compiled with cfg must still be syntactically valid (i.e. parse sucessfully), but nothing more than that.

In the first code, let x = 1; is a normal variable declaration statement, and sss is a trailing expression returning the value of sss from the function. sss is not defined, and thus of course this code is not valid, but it is syntactically valid.

In the second snippet, however, you have sss - that is an expression, and must have a trailing semicolon, but it doesn't. This code is not syntactically valid, and the fact that it is cfg-gated does not matter.

Related