rustrust-cargo

Package with both a library and a binary?


I would like to make a Rust package that contains both a reusable library (where most of the program is implemented), and also an executable that uses it.

Assuming I have not confused any semantics in the Rust module system, what should my Cargo.toml file look like?


Solution

  • Tok:tmp doug$ du -a
    
    8   ./Cargo.toml
    8   ./src/bin.rs
    8   ./src/lib.rs
    16  ./src
    

    Cargo.toml:

    [package]
    name = "mything"
    version = "0.0.1"
    authors = ["me <me@gmail.com>"]
    
    [lib]
    name = "mylib"
    path = "src/lib.rs"
    
    [[bin]]
    name = "mybin"
    path = "src/bin.rs"
    

    src/lib.rs:

    pub fn test() {
        println!("Test");
    }
    

    src/bin.rs:

    extern crate mylib; // not needed since Rust edition 2018
    
    use mylib::test;
    
    pub fn main() {
        test();
    }