Using a Library

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, to link a crate to a new library in Rust, you can use the rustc command's --extern flag and import all of its items under a module with the same name as the library.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/DataStructuresandEnumsGroup(["`Data Structures and Enums`"]) rust(("`Rust`")) -.-> rust/ProjectManagementandOrganizationGroup(["`Project Management and Organization`"]) rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("`Method Syntax`") rust/ProjectManagementandOrganizationGroup -.-> rust/cargo_crates("`Cargo and Crates`") subgraph Lab Skills rust/function_syntax -.-> lab-99338{{"`Using a Library`"}} rust/expressions_statements -.-> lab-99338{{"`Using a Library`"}} rust/method_syntax -.-> lab-99338{{"`Using a Library`"}} rust/cargo_crates -.-> lab-99338{{"`Using a Library`"}} end

Using a Library

To link a crate to this new library you may use rustc's --extern flag. All of its items will then be imported under a module named the same as the library. This module generally behaves the same way as any other module.

// extern crate rary; // May be required for Rust 2015 edition or earlier

fn main() {
    rary::public_function();

    // Error! `private_function` is private
    //rary::private_function();

    rary::indirect_access();
}
## Where library.rlib is the path to the compiled library, assumed that it's
## in the same directory here:
$ rustc executable.rs --extern rary=library.rlib && ./executable
called rary's `public_function()`
called rary's `indirect_access()`, that
> called rary's `private_function()`

Summary

Congratulations! You have completed the Using a Library lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like