What good is lib.rs in Rust?

Asked

Viewed 53 times

5

As shown in this question, in Rust it is possible to import a file (its structs, functions, etc) using the keyword mod. For example, in the following directory structure:

src/
    main.rs
    minhasfuncoes.rs

I can access the functions written in minhasfuncoes.rs adding mod minhasfuncoes at the top of the file main.rs.

However, reading on the internet saw that it is common to create a file called lib.rs in the directory when creating a package. What is this file for lib.rs?

1 answer

5


The archive lib.rs is the entry-point conventional libraries written in Rust.

All the items (functions, structures, enumerations, traits, etc) exported in that entry-point can be accessed by other Crates that depend on your library.

When a CRATE uses another CRATE as a library (this is called dependency), only the public items of lib.rs can be accessed. As, by default, items in a module in Rust are private, only what is explicitly marked as pub in lib.rs is visible to dependents downstream. Private items also do not appear in the automatically generated documentation in Docs.rs.

A Crate can be a binary or a library. A "dependency tree" is formed when Crates begins to depend on other Crates. Dependency management is done by Cargo.

Generally libraries open-source are published in Crates io., but that’s not the only way to make a CRATE available. In addition to relying on libraries published on Crates.io, you can also specify Git repositories, local projects, or other registries as library sources. See more here.

For more details about libraries and the Cargo, Official Book of the Office is a good reference.


By default, when you use the command cargo new to create a project, create a file main.rs in the directory src. This indicates that the project is an executable Crate (also called Binary Crate). The archive main.rs contains the function main which is executed when someone starts its binary.

Already when using the flag --lib to generate a new project, it is created instead of main.rs, lib.rs, what defines the project as a library. The lib.rs is, reiterating, the entry-point items exported by the library.

Rust has chosen to establish well-defined conventions, so that, by default, every project with a lib.rs is considered a library and every project with a main.rs is considered an executable. These conventions can be changed, but this is rarely necessary.

If necessary, a binary and an executable can coexist in the same CRATE.

It is also possible to create a Workspace, ideal for monorepos, but that is beyond the scope of this question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.