2 个版本
| 0.1.1 | 2020 年 8 月 29 日 |
|---|---|
| 0.1.0 | 2020 年 8 月 29 日 |
在 Rust 模式 中排名第 1392
每月下载量 37
在 4 个包中使用 (通过 houtamelo_utils)
10KB
83 行
pluck
pluck! 是一个宏,它创建一个 lambda 表达式,从参数中提取提供的属性。非常适合与迭代器一起使用。
访问
pluck! 提供了许多不同的访问值的方法。
元组索引
提供要提取的索引。
let list = [(0, "a"), (1, "b"), (2, "c")];
let first = list.iter().map(pluck!(.0)).collect::<Vec<_>>();
assert_eq!(first, &[0, 1, 2]);
let second = list.iter().map(pluck!(.1)).collect::<Vec<_>>();
assert_eq!(second, &["a", "b", "c"]);
结构属性
提供要提取的属性名。
struct Person { name: &'static str }
let list = [Person { name: "Alice" }];
let names = list.iter().map(pluck!(.name)).collect::<Vec<_>>();
assert_eq!(names, &["Alice"]);
通过引用
在属性名前加上 & 以通过引用提取。
let list = [(0, "a"), (1, "b"), (2, "c")];
let first = list.iter().map(pluck!(&.0)).collect::<Vec<_>>();
assert_eq!(first, &[&0, &1, &2]);
可变引用
在属性名前加上 &mut 以通过可变引用提取。
let mut list = [(0, "a"), (1, "b"), (2, "c")];
for num in list.iter_mut().map(pluck!(&mut .0)) {
*num += 1;
}
assert_eq!(list, [(1, "a"), (2, "b"), (3, "c")]);
索引类型
pluck! 与实现 Index 和 IndexMut 的类型一起工作。
let list = [[0], [1], [2]];
let first = list.iter().map(pluck!([0])).collect::<Vec<_>>();
assert_eq!(first, &[0, 1, 2]);
let first_ref = list.iter().map(pluck!(&[0])).collect::<Vec<_>>();
assert_eq!(first_ref, &[&0, &1, &2]);
Deref
pluck! 与实现 Deref 和 DerefMut 的类型一起工作。
let list = vec![&0, &1, &2];
let derefed = list.into_iter().map(pluck!(*)).collect::<Vec<_>>();
assert_eq!(derefed, &[0, 1, 2]);
let list = vec![&&&0, &&&1, &&&2];
let derefed = list.into_iter().map(pluck!(***)).collect::<Vec<_>>();
assert_eq!(derefed, &[0, 1, 2]);
组合
pluck! 被设计成允许您任意组合访问。您可以使用 () 指定优先级。
struct Person { name: &'static str }
let mut list = vec![[&Person { name: "Alice" }]];
let derefed = list.iter_mut().map(pluck!((*[0]).name)).collect::<Vec<_>>();
assert_eq!(derefed, &["Alice"]);