Cargo Attributes in Rust Development

RustRustBeginner
Practice Now

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

Introduction

In this lab, it is explained that the crate_type and crate_name attributes in Rust have no effect when using Cargo, the Rust package manager, which is widely used for Rust projects.

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/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/MemorySafetyandManagementGroup(["`Memory Safety and Management`"]) rust/DataTypesGroup -.-> rust/string_type("`String Type`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("`Lifetime Specifiers`") subgraph Lab Skills rust/string_type -.-> lab-99341{{"`Cargo Attributes in Rust Development`"}} rust/function_syntax -.-> lab-99341{{"`Cargo Attributes in Rust Development`"}} rust/expressions_statements -.-> lab-99341{{"`Cargo Attributes in Rust Development`"}} rust/lifetime_specifiers -.-> lab-99341{{"`Cargo Attributes in Rust Development`"}} end

Crates

The crate_type attribute can be used to tell the compiler whether a crate is a binary or a library (and even which type of library), and the crate_name attribute can be used to set the name of the crate.

However, it is important to note that both the crate_type and crate_name attributes have no effect whatsoever when using Cargo, the Rust package manager. Since Cargo is used for the majority of Rust projects, this means real-world uses of crate_type and crate_name are relatively limited.

// This crate is a library
#![crate_type = "lib"]
// The library is named "rary"
#![crate_name = "rary"]

pub fn public_function() {
    println!("called rary's `public_function()`");
}

fn private_function() {
    println!("called rary's `private_function()`");
}

pub fn indirect_access() {
    print!("called rary's `indirect_access()`, that\n> ");

    private_function();
}

When the crate_type attribute is used, we no longer need to pass the --crate-type flag to rustc.

$ rustc lib.rs
$ ls lib*
library.rlib

Summary

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

Other Rust Tutorials you may like