Skip to content

推荐的 Rust 包

· 1 min

bitflags#

用于生成 比特 枚举

// The `bitflags!` macro generates `struct`s that manage a set of flags.
bitflags! {
/// Represents a set of flags.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Flags: u32 {
/// The value `A`, at bit position `0`.
const A = 0b00000001;
/// The value `B`, at bit position `1`.
const B = 0b00000010;
/// The value `C`, at bit position `2`.
const C = 0b00000100;
/// The combination of `A`, `B`, and `C`.
const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits();
}
}
fn main() {
let e1 = Flags::A | Flags::C;
let e2 = Flags::B | Flags::C;
assert_eq!((e1 | e2), Flags::ABC); // union
assert_eq!((e1 & e2), Flags::C); // intersection
assert_eq!((e1 - e2), Flags::A); // set difference
assert_eq!(!e2, Flags::A); // set complement
}

Derive#

derive-new#

自动创建 new 方法

// 基础
#[derive(new)]
struct Bar {
a: i32,
b: String,
}
let _ = Bar::new(42, "Hello".to_owned());
// 根据默认值减少 new 的参数
#[derive(new)]
struct Foo {
x: bool,
#[new(value = "42")]
y: i32,
#[new(default)]
z: Vec<String>,
}
let _ = Foo::new(true);
// 支持参数 into
#[derive(new)]
struct Foo {
#[new(into)]
x: String,
}
let _ = Foo::new("Hello");
#[derive(new)]
struct Foo {
#[new(into_iter = "bool")]
x: Vec<bool>,
}
let _ = Foo::new([true, false]);
let _ = Foo::new(Some(true));
// 支持 enum
#[derive(new)]
enum Enum {
FirstVariant,
SecondVariant(bool, #[new(default)] u8),
ThirdVariant { x: i32, #[new(value = "vec![1]")] y: Vec<u8> }
}
let _ = Enum::new_first_variant();
let _ = Enum::new_second_variant(true);
let _ = Enum::new_third_variant(42);

相关资料#

官方仓库 https://crates.io/

https://lib.rs/

https://blessed.rs/crates

https://github.com/nicoburns/blessed-rs