How do I tell Cargo to build files other than main.rs?

后端 未结 3 913
不知归路
不知归路 2020-12-15 06:36

Here is my directory structure:

lowks@lowkster ~/src/rustlang/gettingrusty $ tree .
.
├── Cargo.lock
├── Cargo.toml
├── foo.txt
├── src
│   ├── boolean_examp         


        
相关标签:
3条回答
  • 2020-12-15 06:46

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

    • binaries
    • libraries
    • benchmarks
    • integration tests
    • examples

    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.

    0 讨论(0)
  • 2020-12-15 06:50

    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.

    0 讨论(0)
  • 2020-12-15 07:10

    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

    0 讨论(0)
提交回复
热议问题