Using a Library

Beginner

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.

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.