【问题标题】:How do I create a closure that takes either u32 or &str and returns u32 or usize respectively?如何创建一个采用 u32 或 &str 并分别返回 u32 或 usize 的闭包?
【发布时间】: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 方法将返回一个实例那个关联的类型)?然后每个实现都可以指定它将返回什么类型。
  • 如果您想支持给定类型的多种返回类型(例如,转换为 usize len 和 String 的复制 &amp;str ),您可以移动 W CValue trait 的泛型类型参数,而不是 @eggyal 所说的关联类型。
  • 请edit 您的问题并粘贴您收到的确切和全部错误 - 这将帮助我们了解问题所在,以便我们提供最佳帮助。有时试图解释错误消息很棘手,实际上错误消息的不同部分很重要。请使用直接运行编译器的消息,而不是 IDE 生成的消息,它可能会尝试为您解释错误。
  • 如果关联类型在这里的工作方式不明显,也许this 会有所帮助。
  • 很高兴您有问题的解决方案!您应该将其作为答案发布,而不是对您的问题进行编辑,然后可能会接受该答案。这样,问题就会在搜索结果中显示为已解决,人们可以对您的答案进行投票,并且您的解决方案可以对未来遇到相同问题的人更有帮助。

标签: generics struct rust traits


【解决方案1】:

感谢一些 cmets,我让它使用关联类型工作。

这是允许我使用&amp;str 或u32 输入调用相同Cacher 实例的工作代码。我实际上实现了两个结构:CStr 和CInt,它们都符合特征CValue。这允许我通过其中任何一个并使用CValue::get() 方法获取值(u32 或&amp;str 的长度与u32 相同):

ma​​in.rs

use crate::closures::{CInt, CStr};

fn is_number(input: &str) -> bool {
    for c in input.chars() {
        println!("Aqui los chars: {}", c);
        if !c.is_numeric() {
            return false;
        }
    }
    true
}

fn main() {
    if is_number(&intensity) {
        let simulated_user_specified_value = CInt::new(intensity.parse::<u32>().unwrap());
        closures::generate_workout(simulated_user_specified_value, simulated_random_number);
    } else {
        let simulated_user_specified_value = CStr::new(&intensity);
        closures::generate_workout(simulated_user_specified_value, simulated_random_number);
    }
}

lib.rs

use std::{collections::HashMap, fmt::Display, hash::Hash, thread, time::Duration};

pub fn generate_workout<X: CValue<ItemOut = u32> + Copy + Eq + Hash>(
    intensity: X,
    random_number: u32,
) {
    let mut struct_clouse = Cacher::new(|num: X| {
        println!("calculating slowly...");
        thread::sleep(Duration::from_secs(2));
        num.get()
    });

    if intensity.get() < 25 {
        println!("Today, do {} pushups!", struct_clouse.value(intensity));
        println!("Next, do {} situps!", struct_clouse.value(intensity));
    } else {
        if random_number == 3 {
            println!("Take a break today! Remember to stay hydrated!");
        } else {
            println!("Today, run for {} minutes!", struct_clouse.value(intensity));
        }
    }
}

pub struct Cacher<T, U, V>
where
    T: Fn(U) -> V,
{
    calculation: T,
    value: HashMap<U, V>,
}

impl<T, U, V> Cacher<T, U, V>
where
    T: Fn(U) -> V,
    U: Eq + Copy + Hash,
    V: PartialOrd + Copy,
{
    pub fn new(calculation: T) -> Cacher<T, U, V> {
        Cacher {
            calculation,
            value: HashMap::new(),
        }
    }

    pub fn value(&mut self, arg: U) -> V {
        match self.value.get(&arg) {
            Some(v) => *v,
            None => {
                let v = (self.calculation)(arg);
                self.value.insert(arg, v);
                v
            }
        }
    }
}

#[derive(Debug, PartialEq, Clone, Copy, Eq, Hash, PartialOrd)]
pub struct CStr<'a> {
    value: &'a str,
}

#[derive(Debug, PartialEq, Clone, Copy, Eq, Hash, PartialOrd)]
pub struct CInt {
    value: u32,
}

impl CInt {
    pub fn new(value: u32) -> CInt {
        CInt { value }
    }
}

pub trait CValue {
    type ItemOut: Display + PartialOrd + Copy;
    fn get(&self) -> Self::ItemOut;
}

impl<'a> CStr<'a> {
    pub fn new(value: &str) -> CStr {
        CStr { value }
    }
}

impl<'a> CValue for CStr<'a> {
    type ItemOut = u32;

    fn get(&self) -> Self::ItemOut {
        self.value.len() as Self::ItemOut
    }
}

impl CValue for CInt {
    type ItemOut = u32;

    fn get(&self) -> Self::ItemOut {
        self.value
    }
}
´´´

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2021-07-28
    • 2023-04-03
    • 2021-11-23
    • 2018-07-25
    相关资源
    最近更新 更多