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 file has a library, and 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 file is always located at src/

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:


name = "my-example"
version = "0.1.0"
authors = ["Alice Ryhl <>"]
edition = "2018"



pub mod module1;
mod module2;

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


use crate::module2;

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


pub(crate) fn module2_fn() -> String {


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


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

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

  • src/
  • src/
  • src/

and the binary consists of:

  • src/
  • src/

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

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 :)

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.