rust 支持compile time的feature toggle,可以在 Cargo.toml 中指定feature

  1. [package]
  2. name = "feature_toggle"
  3. version = "0.1.0"
  4. authors = ["Sean <xujihui1985@gmail.com>"]
  5. edition = "2018"
  6. # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
  7. [dependencies]
  8. [features]
  9. benchmarking = []
  10. mutate_state = ["lazy_static"]
  11. enable_traceing = []
  12. enable_retry = []

key代表feature的名字,后面的[] 代表这个feature依赖的crate,例如 mutate_state 这个feature依赖 lazy_static,那么在打开这个feature后,cargo就会将lazy_static编译进来

通过annotation

  1. fn do_sth() {
  2. println!("we do sth nornmal here");
  3. #[cfg(feature="benchmarking")]
  4. {
  5. println!("benchmarking");
  6. println!("we do sth inside benchmarking");
  7. }
  8. println!("we do sth after benchmarking");
  9. }
  10. fn main() {
  11. do_sth();
  12. }

根据feature不同的实现

  1. #[derive(Debug)]
  2. struct MyStruct {
  3. name: String,
  4. }
  5. #[cfg(feature="mutate_state")]
  6. fn mutate_slice(s: &mut [MyStruct]) {
  7. println!("mutate_state");
  8. for i in s.iter_mut() {
  9. i.name = String::from("ddddd");
  10. }
  11. }
  12. #[cfg(not(feature="mutate_state"))]
  13. fn mutate_slice(s: &mut [MyStruct]) {
  14. println!("do not mutate state");
  15. for i in s {
  16. println!("{:?}", i);
  17. }
  18. }
  19. fn main() {
  20. let mut s = vec![
  21. MyStruct{name: String::from("aaa")},
  22. MyStruct{name: String::from("bbb")},
  23. MyStruct{name: String::from("ccccc")},
  24. ];
  25. mutate_slice(&mut s);
  26. for i in s.into_iter() {
  27. println!("after mutate {:?}", i);
  28. }
  29. }

compile time if expression

  1. fn complie_time_flag() {
  2. if cfg!(feature="enable_traceing") {
  3. println!("starting");
  4. }
  5. println!("in the body of complie_time_flag");
  6. }

compile time const

  1. #[cfg(feature="enable_retry")]
  2. const MAX_RETRY:u32 = 3;
  3. #[cfg(not(feature="enable_retry"))]
  4. const MAX_RETRY:u32 = 0;
  5. fn main() {
  6. if cfg!(feature="enable_retry") {
  7. println!("retry time {}", MAX_RETRY);
  8. }
  9. }

build/run with feature

  1. cargo run --features "mutate_state","enable_traceing","enable_retry"