【发布时间】:2021-06-28 18:39:04
【问题描述】:
这来自 Rust 书的第 13.1 章,我们在其中使用了闭包、记忆和泛型类型。在此示例中,我已经可以将两个不同的闭包传递给结构 (Cacher) 并相应地获取值,但它们有两个是结构的两个不同实例,以便正确处理类型。
我可以构建一个泛型类型,以便结构的同一个实例可以处理接收任一类型并相应地给我值吗?要么是我通过的相同的u32,要么是我通过的&str 的长度。
use std::collections::HashMap;
use std::thread;
use std::time::Duration;
fn main() {
let simulated_user_specified_value = 10;
let simulated_random_number = 7;
generate_workout(simulated_user_specified_value, simulated_random_number);
}
fn generate_workout(intensity: u32, random_number: u32) {
let mut expensive_result = Cacher::new(|num| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
});
if intensity < 25 {
println!("Today, do {} pushups!", expensive_result.value(intensity));
println!("Next, do {} situps!", expensive_result.value(intensity));
} else {
if random_number == 3 {
println!("Take a break today! Remember to stay hydrated!");
} else {
println!(
"Today, run for {} minutes!",
expensive_result.value(intensity)
);
}
}
}
struct Cacher<T, U, V>
where
T: Fn(U) -> V,
{
calculation: T,
values: HashMap<U, Option<V>>,
}
impl<T, U, V> Cacher<T, U, V>
// Generic T is the function where U and V are the parameter and return value respectively for said function.
where
T: Fn(U) -> V,
U: std::cmp::Eq // U must have 3 trait bounds, Eq, Hash, and Copy.
+ std::hash::Hash
+ Copy,
V: Copy, // V must have trait bound Copy.
{
fn new(calculation: T) -> Cacher<T, U, V> {
Cacher {
calculation,
values: HashMap::new(),
}
}
fn value(&mut self, arg: U) -> V {
match self.values.get(&arg) {
// Get the value for the key in the hashmap.
Some(v) => v.unwrap(), // get the value in the option stored in the hashmap.
None => {
let v = (self.calculation)(arg);
self.values.insert(arg, Some(v)); // Put the key/value pair into the hashmap.
v
}
}
}
}
#[cfg(test)]
mod tests {
use super::Cacher;
#[test]
fn call_with_different_values() {
let mut c = Cacher::new(|a| a);
let _v1 = c.value(1);
let v2 = c.value(2);
assert_eq!(v2, 2);
}
#[test]
fn call_with_string_usize() {
let mut c = Cacher::new(|a: &str| a.len());
let v1 = c.value("Three");
assert_eq!(v1, 5);
}
}
我尝试为结构的value 字段构建结构,然后实现一个特征,将它们分组:
struct CStr<'a> {
value: &'a str,
}
struct CInt {
value: u32,
}
trait CValue {
fn get<W: Copy + Eq>(&self) -> W;
}
impl<'a> CValue for CStr<'a> {
fn get<W: Copy + Eq>(&self) -> W {
self.value.len()
}
}
所以这个测试会通过
#[test]
fn call_with_different_values() {
let mut c = Cacher::new(|a| a.get());
let v1 = c.value(1);
let v2 = c.value("two");
assert_eq!(v2, 3);
}
但我被困在这里:
impl<'a> CValue for CStr<'a> {
fn get<W: Copy + Eq>(&self) -> W {
self.value.len() // here
}
}
出现错误:
[rustc E0308] [E] mismatched types expected type parameter `W` found type `usize`
【问题讨论】:
-
我不完全确定你在这里追求什么,但也许你想在
CValue特征中添加一个 associated type (然后它的get方法将返回一个实例那个关联的类型)?然后每个实现都可以指定它将返回什么类型。 -
如果您想支持给定类型的多种返回类型(例如,转换为
usizelen 和String的复制&str),您可以移动WCValuetrait 的泛型类型参数,而不是 @eggyal 所说的关联类型。 -
请edit 您的问题并粘贴您收到的确切和全部错误 - 这将帮助我们了解问题所在,以便我们提供最佳帮助。有时试图解释错误消息很棘手,实际上错误消息的不同部分很重要。请使用直接运行编译器的消息,而不是 IDE 生成的消息,它可能会尝试为您解释错误。
-
如果关联类型在这里的工作方式不明显,也许this 会有所帮助。
-
很高兴您有问题的解决方案!您应该将其作为答案发布,而不是对您的问题进行编辑,然后可能会接受该答案。这样,问题就会在搜索结果中显示为已解决,人们可以对您的答案进行投票,并且您的解决方案可以对未来遇到相同问题的人更有帮助。
标签: generics struct rust traits