模块 & crate & Cargo & Attributes
可见性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
mod my_mod {
// 不可见
fn private_function() {
println!("called `my_mod::private_function()`");
}
// 可见
pub fn function() {
println!("called `my_mod::function()`");
}
// 可以嵌套
pub mod nested {
pub fn function() {
println!("called `my_mod::nested::function()`");
}
}
}
mod my {
// struct默认是私有的
pub struct OpenBox<T> {
pub contents: T,
}
#[allow(dead_code)]
pub struct ClosedBox<T> {
contents: T,
}
impl<T> ClosedBox<T> {
pub fn new(contents: T) -> ClosedBox<T> {
ClosedBox {
contents: contents,
}
}
}
}
|
包可见性
Crates
在Rust中,crates是一个compilation unit,默认是编译成可执行文件,如果是库文件,可以使用,然后在编译可执行文件中使用。
1
2
|
rustc --crate-type=lib rary.rs
rustc executable.rs --extern rary=library.rlib && ./executable
|
Cargo
Cargo是一个Rust源代码管理工具,可以构建各种各样的工具。具体详见cargo
Cargo.toml
[package]
name = "foo"
version = "0.1.0"
authors = ["mark"]
[dependencies]
clap = "2.27.1" # from crates.io
rand = { git = "https://github.com/rust-lang-nursery/rand" } # from online repo
bar = { path = "../bar" } # from a path in the local filesystem
Attributes
1
2
3
4
5
6
7
8
9
|
// 如果没有使用,不报警告
#[allow(dead_code)]
fn unused_function() {}
#[cfg(target_os = "linux")]
fn are_you_on_linux() {
println!("You are running linux!");
}
|
参考