面试题答案
一键面试项目目录结构规划
- 根目录:包含
Cargo.toml
文件,用于定义工作空间。 src
目录:可以选择保留,用于放置通用代码,也可不使用。bin
目录:存放多个二进制可执行文件的源文件,每个二进制文件一个子目录。例如:bin/app1/src/main.rs
bin/app2/src/main.rs
lib
目录:存放库的源文件,如lib/src/lib.rs
。
Cargo.toml 文件配置
- 工作空间定义:在根目录的
Cargo.toml
中定义工作空间:
[workspace]
members = [
"bin/app1",
"bin/app2",
"lib"
]
- 库的
Cargo.toml
:在lib/Cargo.toml
中定义库:
[package]
name = "my_lib"
version = "0.1.0"
edition = "2021"
[lib]
path = "src/lib.rs"
- 二进制文件的
Cargo.toml
:在每个二进制文件的Cargo.toml
中定义,例如bin/app1/Cargo.toml
:
[package]
name = "app1"
version = "0.1.0"
edition = "2021"
[[bin]]
name = "app1"
path = "src/main.rs"
构建命令详细过程
- 构建所有目标平台:
- Linux (x86_64 - unknown - linux - gnu):
rustup target add x86_64-unknown-linux-gnu
cargo build --target x86_64-unknown-linux-gnu
- **macOS (aarch64 - apple - darwin)**:
rustup target add aarch64-apple-darwin
cargo build --target aarch64-apple-darwin
- 构建单个二进制文件:
- Linux (x86_64 - unknown - linux - gnu) 下构建
app1
:
- Linux (x86_64 - unknown - linux - gnu) 下构建
cargo build --target x86_64-unknown-linux-gnu -p app1
- **macOS (aarch64 - apple - darwin) 下构建 `app2`**:
cargo build --target aarch64-apple-darwin -p app2
处理不同目标平台可能存在的依赖差异
- 条件依赖:在
Cargo.toml
中使用target_os
等条件来指定依赖。例如:
[target.'cfg(target_os = "linux")'.dependencies]
linux - specific - dep = "0.1.0"
[target.'cfg(target_os = "macos")'.dependencies]
macos - specific - dep = "0.1.0"
- 特性 (Feature):可以使用特性来启用不同平台的特定代码和依赖。在
Cargo.toml
中定义特性:
[features]
linux - feature = ["linux - specific - dep"]
macos - feature = ["macos - specific - dep"]
然后在代码中通过 cfg
宏来使用特性相关代码:
#[cfg(feature = "linux - feature")]
fn platform_specific_code() {
// Linux 特定代码
}
#[cfg(feature = "macos - feature")]
fn platform_specific_code() {
// macOS 特定代码
}
构建时通过 --features
参数指定特性:
cargo build --target x86_64-unknown-linux-gnu --features linux - feature
cargo build --target aarch64-apple-darwin --features macos - feature