November 2017
Intermediate to advanced
264 pages
5h 45m
English
An executable project, or crate as it is called in Rust, needs to have a startup function main(), but a library crate, to be used in other crates, does not need a function main(). Create a new library crate mylib with cargo as follows:
cargo new mylib
This creates a subfolder src with a source file lib.rs which contains the following:
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}
So, a library crate is created with no code of its own, but it does contain a test template annotated with a cfg(test) attribute. This attribute indicates that the code that follows will only be compiled in test mode. To differentiate with normal library code, use a prefix not in the attribute like this:
#[cfg(not(test))] fn main() { println!("Normal ...Read now
Unlock full access