CodeBlanks Logo Icon CodeBlanks

Binary and library crate

Learn the difference between binary and library crates.

Binary and library crates

A crate is the smallest unit the compiler compiles at a time. There are two kinds: a binary crate (src/main.rs, an executable program with a main function) and a library crate (src/lib.rs, code for others to use). A package is a unit defined by a Cargo.toml, containing at most one library and any number of binaries:

fatura/
├── Cargo.toml
└── src/
    ├── lib.rs        // library: calculations
    ├── main.rs       // main program: use fatura::kdv_ekle;
    └── bin/
        └── rapor.rs  // extra binary: cargo run --bin rapor

Using the library

A binary in the same package reaches the library by the package name:

// src/lib.rs
pub fn kdv_ekle(tutar: f64) -> f64 {
    tutar * 1.20
}

// src/main.rs
use fatura::kdv_ekle;

fn main() {
    println!("{:.2}", kdv_ekle(100.0));
}

Since the exercise has no second file, we'll imitate the library with a mod.

Practice Library and program

Inside mod fatura, write pub fn kdv_ekle(tutar: f64) -> f64 (adds 20 percent). In main, bring it in with use fatura::kdv_ekle; and print the result of kdv_ekle(100.0) with {:.2}.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
mod fatura {
    pub fn kdv_ekle(tutar: f64) -> f64 {
        tutar * 1.20
    }
}

use fatura::kdv_ekle;

fn main() {
    println!("{:.2}", kdv_ekle(100.0));
}

Expected output

120.00

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What's the benefit of putting logic in <code>lib.rs</code> and input/output in <code>main.rs</code>?

  • The logic becomes testable and reusable in other programs Correct answer
  • Compilation always gets faster
  • main.rs isn't required
  • No difference

Explanation: Integration tests can only reach the library crate; main.rs should stay a thin shell.

2 Library root

Question
fatura/
└── src/
    ├── ____    // library crate
    └── main.rs   // binary crate
Answer
fatura/
└── src/
    ├── lib.rs    // library crate
    └── main.rs   // binary crate

Explanation: The library crate's root file is src/lib.rs.

3 File and role

Term Meaning
src/main.rs Main binary
src/lib.rs Library
src/bin/rapor.rs Extra binary
Cargo.toml Package definition

All lessons in Intermediate