Rust特性总结——#[]
发布时间: 2025-08-07 09:29
|
作者: xueyusky
|
状态: published
|
更新时间: 2025-08-07 10:28
# Rust的#[]特性
## 条件编译——#[cfg()]
#[cfg()]是Rust的条件编译机制,允许根据不同条件选择性编译代码。
### 基本语法
```rust
#[cfg(condition)]
fn some_funtion(){
//只有条件满足才编译这个函数
}
```
### 常用条件类型
#### 1. 目标操作系统(target_os)
```rust
#[cfg(target_os = "windows")]
fn windows_specific_function(){
//只有在windows系统上才编译
println!("这个函数只在windows系统编译");
}
#[cfg(target_os = "linux")]
fn linux_specific_function(){
// 只有在linux系统上才编译
println!("这个函数只在linux系统上编译");
}
#[cfg(target_os = "macos")]
fn macos_specific_function(){
println!("这个函数只在macOS上编译");
}
// 使用示例
fn main(){
#[cfg(target_os = "windows")]
{
println!("运行在WIndows系统上");
windows_specification_function();
}
#[cfg(target_os = "linux")]
{
println!("运行在Linux系统上");
linux_specification_function();
}
}
```
#### 2. 目标架构(target_arch)
```rust
#[cfg(target_arch = "x86_x64")]
fn x64_optimized_function(){
println!("针对x86_x64架构优化的函数");
}
#[cfg(target_arch = "aarch64")]
fn arm64_optimized_function(){
println!("针对ARM64架构优化的函数");
}
#[cfg(target_arch = "wasm32")]
fn wasm_function(){
println!("WebAssembly专用函数");
}
```
#### 3. 编译模式(debug_assertions)
```rust
#[cfg(debug_assertions)]
fn debug_only_function(){
println!("这个函数只在debug模式下编译");
}
#[cfg(not(debug_assertions))]
fn release_only_function(){
println!("这个函数只在release模式下编译");
}
fn main()
{
#[cfg(debug_assertions)]
println!("当前是debug模式");
#[cfg(not(debug_assertions))]
println!("当前是release模式");
}
```
#### 4. 功能特性(feature)
```rust
// 在Cargo.toml中定义[feature],格式如下:
// [feature]
// networking = []
// database = []
// default = ["networking"]
#[cfg(feature = "networking")]
mod networking() {
pub fn send_request(){
println!("发送网络请求");
}
}
#[cfg(feature = "database")]
mod database{
pub fn database() {
println!("连接数据库");
}
}
#[cfg(all(feature = "networking", feature = "database"))]
fn full_stack_function(){
println!("需要网络和数据库功能");
}
```
# 逻辑组合
## 1. `all()` - 所有条件都必须满足
```rust
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn linux_x64_function() {
println!("只在 Linux x86_64 上编译");
}
#[cfg(all(feature = "ssl", not(debug_assertions)))]
fn secure_release_function() {
println!("需要 SSL 功能且在 release 模式");
}
```
## 2. `any()` - 任一条件满足即可
```rust
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn unix_like_function() {
println!("在类 Unix 系统上编译");
}
#[cfg(any(feature = "mysql", feature = "postgresql"))]
fn database_function() {
println!("支持任一数据库");
}
```
## 3. `not()` - 条件不满足时
```rust
#[cfg(not(target_os = “windows”))]
fn non_windows_function(){
println!("非windows系统");
}
#[cfg(not(featrue = "std")]
fn no_std_funtion(){
println!("无标准库环境");
}
```
# 实际应用示例
## 1. 平台特定的文件操作
```rust
use std::path::Path;
#[cfg(target_os = "windows")]
fn get_config_dir() -> &'static str {
"C:\\ProgramData\\MyApp"
}
#[cfg(target_os = "linux")]
fn get_config_dir() -> &'static str {
"/etc/myapp"
}
#[cfg(target_os = "macos")]
fn get_config_dir() -> &'static str {
"/Library/Application Support/MyApp"
}
// 使用配置目录
fn load_config() {
let config_path = get_config_dir();
println!("配置文件路径: {}", config_path);
}
```
## 2. 调试和发布版本的不同行为
```rust
struct Logger;
impl Logger {
#[cfg(debug_assertions)]
fn log(&self, message: &str) {
println!("[DEBUG] {}: {}", chrono::Utc::now(), message);
}
#[cfg(not(debug_assertions))]
fn log(&self, message: &str) {
// 在 release 版本中可能写入文件或发送到日志服务
eprintln!("[INFO] {}", message);
}
}
// 条件编译的宏
macro_rules! debug_println {
($($arg:tt)*) => {
#[cfg(debug_assertions)]
println!($($arg)*);
};
}
fn main() {
let logger = Logger;
logger.log("应用程序启动");
debug_println!("这条消息只在 debug 模式显示");
}
```
## 3. 功能特性的条件编译
```rust
// Cargo.toml
// [features]
// json_support = ["serde_json"]
// xml_support = ["quick-xml"]
// default = ["json_support"]
pub enum DataFormat {
#[cfg(feature = "json_support")]
Json,
#[cfg(feature = "xml_support")]
Xml,
Plain,
}
pub struct DataProcessor;
impl DataProcessor {
#[cfg(feature = "json_support")]
pub fn process_json(&self, data: &str) -> Result<String, Box<dyn std::error::Error>> {
// 使用 serde_json 处理
Ok(format!("JSON 处理结果: {}", data))
}
#[cfg(feature = "xml_support")]
pub fn process_xml(&self, data: &str) -> Result<String, Box<dyn std::error::Error>> {
// 使用 quick-xml 处理
Ok(format!("XML 处理结果: {}", data))
}
pub fn process(&self, data: &str, format: DataFormat) -> Result<String, Box<dyn std::error::Error>> {
match format {
#[cfg(feature = "json_support")]
DataFormat::Json => self.process_json(data),
#[cfg(feature = "xml_support")]
DataFormat::Xml => self.process_xml(data),
DataFormat::Plain => Ok(data.to_string()),
}
}
}
```
## 4. 测试代码的条件编译
```rust
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(2, 3), 5);
}
#[cfg(feature = "extended_tests")]
#[test]
fn test_add_extended() {
assert_eq!(add(-1, 1), 0);
assert_eq!(add(0, 0), 0);
}
}
// 基准测试(需要 nightly 版本)
#[cfg(all(test, feature = "bench"))]
mod benches {
use super::*;
use test::Bencher;
#[bench]
fn bench_add(b: &mut Bencher) {
b.iter(|| add(1, 2));
}
}
```
# 自定义配置
## 1. 环境变量条件
```rust
// 通过环境变量控制编译
#[cfg(env = "CUSTOM_BUILD")]
fn custom_build_function() {
println!("自定义构建版本");
}
// 在构建时设置: CUSTOM_BUILD=1 cargo build
```
## 2. 自定义 cfg 标志
```rust
// 在 build.rs 中设置自定义标志
// println!("cargo:rustc-cfg=custom_feature");
#[cfg(custom_feature)]
fn custom_feature_function() {
println!("自定义功能已启用");
}
```
# 最佳实践
## 1. 避免代码重复
```rust
// 不好的做法
#[cfg(target_os = "windows")]
fn get_separator() -> char { '\\' }
#[cfg(not(target_os = "windows"))]
fn get_separator() -> char { '/' }
// 更好的做法
fn get_separator() -> char {
#[cfg(target_os = "windows")]
return '\\';
#[cfg(not(target_os = "windows"))]
return '/';
}
```
## 2. 使用 cfg\_if 宏简化复杂条件
```rust
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(target_os = "windows")] {
fn platform_specific_code() {
println!("Windows 特定代码");
}
} else if #[cfg(target_os = "linux")] {
fn platform_specific_code() {
println!("Linux 特定代码");
}
} else {
fn platform_specific_code() {
println!("其他平台代码");
}
}
}
```
## 3. 文档中标注条件
```rust
/// 这个函数只在启用网络功能时可用
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "networking")]
/// use myapp::send_data;
///
/// # #[cfg(feature = "networking")]
/// send_data("Hello, world!");
/// ```
#[cfg(feature = "networking")]
pub fn send_data(data: &str) {
println!("发送数据: {}", data);
}
```