Practicing on creating a library

Hi guys I wanted to practice on how to create a library.

So to make sure I am clear, a library is nothing but a crate, right? And it is like just calling a function in the bin file from the lib file, am I correct?

And if this is true, then do I create the library inside the main project, right?

Any project that has a lib.rs file has a library, and lib.rs is the root of the library. If you also have binaries in the same project, then you can access the library with use your_package_name::stuff;

And the library folder should be located inside your binary project?

The lib.rs file is always located at src/lib.rs.

You may want to use cargo new --lib <PROJECT_NAME> as it will set up the scaffolding for you.

@alice @jjpe

Do I run this inside a binary project?

That command creates a new project that only has a library. You don't run it in an existing project.

Oh ok so if I ran this, how would I link it the binary to the library?

Here is an example project with both a library and binary:

Cargo.toml

[package]
name = "my-example"
version = "0.1.0"
authors = ["Alice Ryhl <alice@ryhl.io>"]
edition = "2018"

[dependencies]

src/lib.rs

pub mod module1;
mod module2;

pub fn library_fn() -> String {
    format!("Hello {}", crate::module2::module2_fn())
}

src/module1.rs

use crate::module2;

pub fn module1_fn() -> String {
    "From module 1".to_string()
}
pub fn module1_fn2() -> String {
    module2::module2_fn()
}

src/module2.rs

pub(crate) fn module2_fn() -> String {
    "world!".to_string()
}

src/main.rs

mod main_helper;
use my_example::module1::module1_fn2;

fn main() {
    println!("{}", crate::main_helper::get_hello());
    println!("{}", my_example::library_fn());
    println!("{}", my_example::module1::module1_fn());
    println!("{}", module1_fn2());
}

src/main_helper.rs

pub fn get_hello() -> String {
    "Hello World!".to_string()
}

In this example, the library consists of the following files:

  • src/lib.rs
  • src/module1.rs
  • src/module2.rs

and the binary consists of:

  • src/main.rs
  • src/main_helper.rs

To determined whether a file is part of the binary or library, you should see whether the mod filename statement is in the lib.rs or main.rs file. You should not mention a file in both main.rs and lib.rs with a mod statement. If you want to access it from both, put the mod statement in lib.rs and use a use statement in main.rs.

1 Like

So in the src folder for the binary, should I run cargo new library --bin, is that ok?

I don't understand the question. src is a folder, not a file.

Oh sorry I meant folder, I changed the name from file to folder.

You should not run cargo new inside an existing project. Its purpose is to create a new project. It would create a new src folder.

1 Like

I think I got it now thanks though :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.