rust feature h和 workspace相关知识 (十一)
feature 相关作用和描述
在 Rust 中,features(特性) 是一种控制可选功能和依赖的机制。它允许你在编译时根据不同的需求启用或禁用某些功能,优化构建,甚至改变代码的行为。Rust 的特性使得你可以轻松地为库提供不同的配置,或者在不同的环境中使用不同的功能
1.新建一个项目 study_feature_2025_1_23
Cargo.toml
[package]
name = "study_feature_2025_1_23"
version = "0.1.0"
edition = "2021"
publish = ["crates-io"]
[dependencies]
serde = {version = "1.0.217", features = ["derive"],optional = true}
rgb = {version = "0.8.43", features = ["serde"],optional = true}
[features]
color = ["dep:rgb"] # 依赖 rgb 项目
shapes = ["color","dep:serde","rgb?/serde"] # 依赖加载 color,serde, 如果使用了 rgb 则加载 serde 特性
default = ["color"] # 默认开启 color feature
- lib.rs 代码如下
pub fn draw_line(x: i32, y: i32) {
println!("Drawing a line at ({}, {})", x, y);
}
#[cfg(feature = "color")] // 这个是设置这个模块为一个feature : color
pub mod color {
pub use rgb::RGB;
pub fn draw_line(x: i32,y: i32, color: &RGB<u16>){
println!("{color}, Drawing a line at ({}, {})", x, y);
}
}
#[cfg(feature = "shapes")] // 这个是设置这个模块为一个feature : shapes
pub mod shapes {
use serde::{Deserialize, Serialize};
use rgb::RGB;
#[derive(Debug,Serialize,Deserialize)]
pub struct Rectangle {
pub width: u32,
pub height: u32,
pub color: RGB<u16>,
}
}
2.新建一个项目 study_feature_consumer_2025_1_23
Cargo.toml
[package]
name = "study_feature_consumer_2025_1_23"
version = "0.1.0"
edition = "2021"
publish = ["crates-io"]
[dependencies]
study_feature_2025_1_23 = {path = "../study_feature_2025_1_23",default-features = false,features = ["shapes"]}
# default-features 是false 关闭所有默认feature
- main.rs
use study_feature_2025_1_23::color;
use study_feature_2025_1_23::shapes;
fn main() {
study_feature_2025_1_23::draw_line(1, 2);
let color = color::RGB {
r: 0,
g: 0,
b: 0,
};
color::draw_line(1, 2, &color);
println!("形状: {:?}", shapes::Rectangle {
width: 1,
height: 2,
color,
});
}
workspace
[workspace]
resolver = "2"
members = [
"hecto3_8",
"hecto3_9",
"hecto3_10",
"hecto3_11",
"hecto4_1",
"hecto4_3",
"hecto4_4",
"hecto4_5",
"hecto4_6",
"hecto4_7",
"hecto4_8",
"hecto4_9",
"hecto5_1",
"hecto5_2",
"hecto5_3",
"hecto5_4",
"hecto5_5",
"hecto5_6",
"hecto5_7",
"hecto5_8",
"hecto5_9",
"hecto5_10",
"hecto5_11",
]
[workspace.dependencies] # 依赖的全局包
env_logger = "0.11.3"
[profile.release]
lto = true
opt-level = "z"
panic = "abort"
# 编译器能进行全局优化
codegen-units = 1
[profile.dev]