Open In App

Rust – Using a Library

Last Updated : 26 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Rust is a blazing fast and memory-efficient static compiled language with a rich type system and ownership model. It can be used to power performance-critical services while guaranteeing memory safety and thread-safety, empowering developers to debug at compile-time. In Rust, we can create libraries. This can be done by creating a library and then linking it to a crate. 

Creating a Rust Library:

Step 1: We create a file named gfg.rs that has the content of our library.

Example 1:

Rust




// Rust code for creating a library
pub fn pub_func() {
    println!("Inside public function");
}
 
fn pvt_func() {
    println!("Calling pvt function");
}
 
pub fn indirect_fn_access() {
    print!("Accessing indirect functions ");
 
    pvt_func();
}


Step 2:  For prefixing libraries with “lib”, we rename the file after declaring the crate files. This is allowed by the rust compiler (rustc) that enables us to pass the –crate-name option 

 

Here, we pass the commands by using the crate option:

rustc –crate-type=lib gfg.rs

ls lib*

Step 3: The above commands as we can clearly see generates the file  “library.rlib”  and all the libraries get prefixed with “lib” and by default, they are named after their create file. The default name is overridden once we pass the crate attribute.

Using a Library in Rust:

Once our library is created we can use it to link a new library via using a crate and the –extern flag provided by the rust compiler. Once we use it, then the items would be imported under a module whose name is the same as that of the library and we can expect the module to show similar behavior as other modules.

Here, we are creating a new file named executable.rs and inside the file, we are accessing the public function and the indirect_fun_access function in the following way:

Example 2:

Rust




// Rust code for use a Library
fn main() {
    gfg::pub_func();
 
    gfg::indirect_fn_access();
}


The file structure:

 

Now, to execute the module, we use the command:

 rustc executable.rs --extern
 gfg=libgfg.rlib --edition=2018
 && ./executable

Here, the library is libgfg.rlib, and the file being executable is executable.rs

Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads