39

Here is my directory structure:

lowks@lowkster ~/src/rustlang/gettingrusty $ tree .
.
├── Cargo.lock
├── Cargo.toml
├── foo.txt
├── src
│   ├── boolean_example.rs
│   ├── function_goodbye_world.rs
│   ├── listdir.rs
│   ├── looping.rs
│   ├── main.rs
│   ├── pattern_match.rs
│   └── write_to_file.rs
└── target
    ├── build
    ├── deps
    ├── examples
    ├── gettingrusty
    └── native

6 directories, 11 files

When I run 'cargo build', it seems to only build main.rs. How should I change Cargo.toml to build the rest of the files too?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Muhammad Lukman Low
  • 8,177
  • 11
  • 44
  • 54

4 Answers4

40

Put other.rs file into bin subfolder of src folder (./src/bin/other.rs). And run cargo build --bin other or cargo run --bin other

rofrol
  • 14,438
  • 7
  • 79
  • 77
Andriy Viyatyk
  • 395
  • 1
  • 3
  • 2
18

The Rust compiler compiles all the files at the same time to build a crate, which is either an executable or a library. To add files to your crate, add mod items to your crate root (here, main.rs) or to other modules:

mod boolean_example;
mod function_goodbye_world;
mod listdir;
mod looping;
mod pattern_match;
mod write_to_file;

To access items defined in another module from your crate root, you must qualify that item with the module name. For example, if you have a function named foo in module looping, you must refer to it as looping::foo.

You can also add use statements to import names in the module's scope. For example, if you add use looping::foo;, then you can just use foo to refer to looping::foo.

For more information, see Separating Modules into Different Files in The Rust Programming Language.

Francis Gagné
  • 60,274
  • 7
  • 180
  • 155
18

There are a few different types of binaries or targets that cargo recognizes:

For example, if the file boolean_example.rs is a standalone example that you want to run you can put in inside an examples directory and tell cargo about it like so:

[[example]]
name = "boolean" # examples/boolean.rs

This lets you invoke your example with cargo run --example boolean

Read the cargo book's page on package layout as well to see how these target directories can be structured.

Gwen
  • 191
  • 1
  • 3
-3

you can include your testing in the main.rs file as following >>

Filename: src/main.rs

#[cfg(test)]
mod tests {
    use super::*;
  #[test]
 fn this_test_will_pass() {
    let value = 4;
    assert_eq!(4, value);
  }

  #[test]
  fn this_test_will_fail() {
    let value = 8;
    assert_eq!(5, value);
  }
}

Or call them from your tests file. then run them using test command: cargo test

from filename: lib/tests.rs

mod tests;

tests::run();

in this case main.rs will be built but only tests.rs file will be executed.

more prove:

exmaple

kimo_ouz
  • 323
  • 4
  • 7