Rust 开发中的 Cargo 属性

Beginner

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

简介

在本实验中,将解释在使用广泛应用于 Rust 项目的 Rust 包管理器 Cargo 时,Rust 中的 crate_typecrate_name 属性无效。

注意:如果实验未指定文件名,你可以使用任何你想要的文件名。例如,你可以使用 main.rs,通过 rustc main.rs &&./main 进行编译和运行。

包(Crate)

crate_type 属性可用于告知编译器一个包是二进制可执行文件还是库(甚至是哪种类型的库),而 crate_name 属性可用于设置包的名称。

不过,需要注意的是,在使用 Rust 包管理器 Cargo 时,crate_typecrate_name 属性都完全无效。由于 Cargo 被用于大多数 Rust 项目,这意味着 crate_typecrate_name 在实际中的使用相对有限。

// 此包是一个库
#![crate_type = "lib"]
// 该库名为 "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();
}

当使用 crate_type 属性时,我们不再需要向 rustc 传递 --crate-type 标志。

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

总结

恭喜你!你已完成“包(Crate)”实验。你可以在 LabEx 中练习更多实验以提升你的技能。