Rust package with both a library and a binary?

Andrew Wagner picture Andrew Wagner · Nov 15, 2014 · Viewed 61k times · Source

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?

Answer

Doug picture Doug · Nov 15, 2014
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 <[email protected]>"]

[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();
}