Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between binary and library in Rust? [duplicate]

What's the difference between binary and library in Rust? I read The Cargo Book, but couldn't understand it well.

I generated two folders using cargo new a --bin and cargo new b --lib, however, both of them look the same inside. What are the purposes of --bin and --lib? And what are the difference between them?

like image 390
Poipoi Avatar asked Jun 13 '26 00:06

Poipoi


2 Answers

A binary crate should generate an executable (or multiple) that can be installed in the user's path and can be executed as usual.

The purpose of a library crate on the other hand is not to create executables but rather provide functionality for other crates to depend on and use.

Also they do differ in their structure:

✦2 at [22:50:27] ➜ cargo new --bin somebinary
✦2 at [22:50:29] ➜ cargo new --lib somelib
     Created library `somelib` package
✦2 at [22:50:34] ➜ tree somebinary/
somebinary/
├── Cargo.toml
└── src
    └── main.rs
1 directory, 2 files
✦2 at [22:50:41] ➜ tree somelib/
somelib/
├── Cargo.toml
└── src
    └── lib.rs

You can also find more information in this rust-lang forum thread: https://users.rust-lang.org/t/what-is-the-difference-between-cargo-new-lib-and-cargo-new-bin/19009

like image 50
bergercookie Avatar answered Jun 15 '26 05:06

bergercookie


One creates an src/main.rs and other creates src/lib.rs. They are different in the nature of the files which are created. Differences lies in whether you are interested in creating a library or interested in creating a binary Are you sure you ran those exact same commands?

(ins)temp->tree
.
├── a
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── b
    ├── Cargo.toml
    └── src
        └── lib.rs
like image 34
apatniv Avatar answered Jun 15 '26 04:06

apatniv