我想使用Iterator::find的libusb::Devices对象,它具有像这样的签名:
fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
where Self: Sized, P: FnMut(&Self::Item) -> bool
Run Code Online (Sandbox Code Playgroud)
我想找一个具有特定功能的设备vendor_id,这需要Device::device_descriptor在每个设备上调用.但是,该device_descriptor方法需要&mut每个设备一个,而find方法只给出一个&.
这是否意味着它不可能在任何的迭代器的方法(使用可变方法find,filter等等)?
这是我正在努力工作的例子:
let mut device = context
.devices()
.unwrap()
.iter()
.find(&mut |dev: &libusb::Device| {
dev.device_descriptor().unwrap().vendor_id() == vendor_id
})
.unwrap();
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
error: cannot borrow immutable borrowed content `*dev` as mutable
Run Code Online (Sandbox Code Playgroud) 是否可以创建一个宏来将非元组参数转换为元组?我想要这样的东西:
assert_eq!(tuplify!(1, (2, 3), 4), ((1,), (2, 3), (4,)));
Run Code Online (Sandbox Code Playgroud)
我试图创建这样的宏但无法这样做.我遇到的问题是每个参数可以有两种形式之一,我无法弄清楚如何指定它.
假设我有以下示例:
struct Client {
email: String,
phone: String,
details: String
}
fn main() {
let mut clients: Vec<Client> = Vec::new();
clients.push(Client {
email: "john@gmail.com".to_string(),
phone: "0123456789".to_string(),
details: "custom details".to_string(),
});
clients.push(Client {
email: "john@gmail.com".to_string(),
phone: "0123456789".to_string(),
details: "other details".to_string(),
});
clients.push(Client {
email: "james@gmail.com".to_string(),
phone: "9876543210".to_string(),
details: "test".to_string(),
});
}
Run Code Online (Sandbox Code Playgroud)
通过检查email和phone在Client? 例如 - 在上面的例子中会发现一个重复。
我HashMap使用默认值实现了换行,我想知道它是否安全.
当get被调用时,内部映射可以被调整大小和值(与先前获得的参考文献get)将被指向无效地址.我尝试使用"计算机科学中的所有问题都可以通过另一层次的间接解决"的想法来解决这个问题(Butler Lampson).我想知道这个技巧是否使这段代码安全.
use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::hash::Hash;
pub struct DefaultHashMap<I: Hash + Eq, T: Clone> {
default: T,
map: UnsafeCell<HashMap<I, Box<T>>>,
}
impl<I: Hash + Eq, T: Clone> DefaultHashMap<I, T> {
pub fn new(default: T) -> Self {
DefaultHashMap {
default: default,
map: UnsafeCell::new(HashMap::new()),
}
}
pub fn get_mut(&mut self, v: I) -> &mut T {
let m = unsafe { &mut *self.map.get() };
m.entry(v).or_insert_with(|| Box::new(self.default.clone()))
}
pub fn get(&self, …Run Code Online (Sandbox Code Playgroud) 这段代码(游乐场):
fn resolve_score(string: String) -> u16 {
let mut score: u16;
string
.drain(..)
.map(|char| {
match char {
'a' => score += 1,
'f' => score += 4,
_ => ()
};
})
.collect();
}
Run Code Online (Sandbox Code Playgroud)
生成此错误:
<anon>:16:14: 16:21 error: unable to infer enough type information about `_`; type annotations or generic parameter binding required [E0282]
<anon>:16 .collect();
^~~~~~~
<anon>:16:14: 16:21 help: see the detailed explanation for E0282
error: aborting due to previous error
Run Code Online (Sandbox Code Playgroud)
我怎样才能解决这个问题?