简体   繁体   English

Rust 中的 Generics - 迭代和索引通用 vec(频率计数函数)

[英]Generics in Rust - Iterate and index generic vec (frequency count function)

I feel this should be easy, but I'm stuck I can easily do a frequency count of a specific type (like u8), but how can I make it generic to allow counting u32s as well?我觉得这应该很容易,但我被卡住了,我可以轻松地对特定类型(如 u8)进行频率计数,但我怎样才能使其通用以允许也对 u32 进行计数?

// Type specific works
fn freqs_u8(data: &[u8], size: usize) -> Vec<u32> {
    data.iter().fold(vec![0_u32; size], |mut freqs, &el| {
        freqs[el as usize] += 1;
        freqs
    })
}

// Not working generic because generic el cannot be typecast to size
fn freqs<T>(data: &[T], size: usize) -> Vec<u32> {
    data.iter().fold(vec![0_u32; size], |mut freqs, &el| {
        freqs[el as usize] += 1;
        freqs
    })
}

I've played with where restrictions on T, but to no avail.我玩过 T 的 where 限制,但无济于事。 I've try creating an enum for T that is either a u8 or u32, but I'm not successful there either.我已经尝试为 T 创建一个 u8 或 u32 的枚举,但我也没有成功。

I wonder if I just don't know how to ask the question in the documentation - I've been looking in vain for days.我想知道我是否只是不知道如何在文档中提出问题 - 我已经徒劳地寻找了好几天了。

The problem is that there is no trait to specify for as .问题是没有要为as指定的特征。

There are two possible options:有两种可能的选择:

  1. Use num-traits , that provides the AsPrimitive trait:使用num-traits ,它提供AsPrimitive特征:
fn freqs<T: num_traits::AsPrimitive<usize>>(data: &[T], size: usize) -> Vec<u32> {
    data.iter().fold(vec![0_u32; size], |mut freqs, &el| {
        freqs[el.as_()] += 1;
        freqs
    })
}
  1. Or better, useTryInto , and panic if the value is too big for usize (this will be optimized away for types where usize is always big enough, eg u32 on 32bit and 64bit platforms):或者更好的是,使用TryInto ,如果值对于usize来说太大(这将针对usize总是足够大的类型进行优化,例如 32 位和 64 位平台上的u32 ):
fn freqs<T>(data: &[T], size: usize) -> Vec<u32>
where
    T: TryInto<usize> + Copy,
    T::Error: std::fmt::Debug,
{
    data.iter().fold(vec![0_u32; size], |mut freqs, &el| {
        freqs[el.try_into().unwrap()] += 1;
        freqs
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM