Crate skeleton
- Rust course
- Intermediate
- Lesson 25/115
- 6 min
Set up a library crate with lib.rs.
Library project: skeleton
In this project we'll write a small library crate that keeps books on a shelf and searches them. A library crate offers an API for others to use instead of a main:
$ cargo new --lib kitaplik
$ tree kitaplik
kitaplik
├── Cargo.toml
└── src
└── lib.rsIn the exercises we'll write everything in a single file, inside a mod kitaplik { .. } block; in a real project this content lives in src/lib.rs and is used from outside with use kitaplik::Kitap;.
Modules and visibility
Everything inside a module is private by default. Items to be used from outside are marked with pub; even if the struct itself is pub, its fields must also be pub:
mod kitaplik {
pub struct Kitap {
pub ad: String,
pub yazar: String,
pub yil: u16,
}
}
use kitaplik::Kitap;In the first version we leave the fields open; in the next lesson we'll encapsulate the API.
Practice First book
Inside mod kitaplik, define Kitap { ad: String, yazar: String, yil: u16 } with pub fields. In main, bring it in with use, create the book Tutunamayanlar / Oğuz Atay / 1972 and print it as ad - yazar (yil).
Starter code
fn main() {
// buraya yaz
}Sample solution
mod kitaplik {
pub struct Kitap {
pub ad: String,
pub yazar: String,
pub yil: u16,
}
}
use kitaplik::Kitap;
fn main() {
let k = Kitap {
ad: String::from("Tutunamayanlar"),
yazar: String::from("Oğuz Atay"),
yil: 1972,
};
println!("{} - {} ({})", k.ad, k.yazar, k.yil);
}Expected output
Tutunamayanlar - Oğuz Atay (1972)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which file does <code>cargo new --lib</code> create?
- src/main.rs
- lib/mod.rs
- src/kitaplik.rs
- src/lib.rs Correct answer
Explanation: A library crate's root is src/lib.rs, a binary crate's root is src/main.rs. A package can contain both.
2 Make it public
mod kitaplik {
____ struct Kitap {
pub ad: String,
}
}
mod kitaplik {
pub struct Kitap {
pub ad: String,
}
}
Explanation: pub makes the item accessible from outside the module.
3 Item and visibility
| Term | Meaning |
|---|---|
struct Kitap (no pub) |
Module only |
pub struct Kitap |
Type visible outside |
pub ad: String |
Field visible outside |
use kitaplik::Kitap |
Brings into scope |