我试图实现一个位矢量库作为练习,但是当我想要定义一个泛型类型参数的默认值时遇到了麻烦。默认泛型类型参数不能推断
这是代码的摘录,我有:
extern crate num;
use std::cmp::Eq;
use std::ops::{BitAnd,BitOrAssign,Index,Shl};
use num::{One,Zero,Unsigned,NumCast};
pub trait BitStorage: Sized +
BitAnd<Self, Output = Self> +
BitOrAssign<Self> +
Shl<Self, Output = Self> +
Eq + Zero + One + Unsigned + NumCast + Copy {}
impl<S> BitStorage for S where S: Sized +
BitAnd<S, Output = S> +
BitOrAssign<S> +
Shl<S, Output = S> +
Eq + Zero + One + Unsigned + NumCast + Copy {}
pub struct BitVector<S: BitStorage = usize> {
data: Vec<S>,
capacity: usize
}
impl<S: BitStorage> BitVector<S> {
pub fn with_capacity(capacity: usize) -> BitVector<S> {
let len = (capacity/(std::mem::size_of::<S>() * 8)) + 1;
BitVector { data: vec![S::zero(); len], capacity: capacity }
}
//...
}
而且我想用它如下:
let vec = BitVector::with_capacity(1024);
不过,我得到一个编译错误:
lib.rs:225:24: 225:48 error: unable to infer enough type information about
_
; type annotations or generic parameter binding required [E0282]
lib.rs:225 let vec_1000 = BitVector::with_capacity(1000);
^~~~~~~~~~~~~~~~~~~~~~~~
lib.rs:225:24: 225:48 help: runrustc --explain E0282
to see a detailed explanation
为了给代码提供更多的上下文,BitStorage
的当前有效类型包括(但不限于* )u8
,u16
,u32
,u64
和usize
。 (*)我认为你可以编写一个自定义的u128
实现(就像例子),如果你实现了该类型的所有特征。
关于这个问题的谷歌搜索后,我发现RFC 213似乎并不be stable yet。但另一方面HashMap目前稳定是使用默认值,所以它应该工作,对不对?