【发布时间】:2017-09-10 02:59:26
【问题描述】:
Rust 的类型系统不会泛化大小,但对于 type associated constants(Rust 1.20 中的新功能),我认为可以通过在类型上声明一个常量大小来实现这一点。
给定在 Rust 中对固定大小数组进行操作的函数,使用类型常量来声明采用任意数组大小或至少是预定义大小范围 (1..32) 的函数是否可能/实用。
以这个小的数学 API 为例:
// Cut down example of a math API
// Could be changed at compile time, otherwise quite limiting.
pub const DIMS: usize = 3;
pub fn sq(a: f64) -> f64 { a }
pub fn len_squared_vnvn(v0: &[f64; DIMS], v1: &[f64; DIMS]) -> f64 {
let mut d = 0.0;
for j in 0..DIMS {
d += sq(v0[j] - v1[j]);
}
return d;
}
fn imul_vn_fl(v0: &mut [f64; DIMS], f: f64) {
for j in 0..DIMS {
v0[j] *= f;
}
}
可以将DIMS 移动到类型关联的常量中,以便...
-
imul_vn_fl等函数可用于任意固定大小的数组。 - 支持传递原始固定大小的数组类型,例如:
[f64; SOME_CONSTANT_NUMBER],或者更可能是零成本转换为包装[f64; #]并定义DIMS类型常量的类型。 - 使用
std::convert::From/Into以避免在调用时显式编写强制转换。 - 生成的代码应该与使用常量大小一样有效(无运行时大小检查)。
我在想象这样的事情:
// this would be a macro to avoid re-writing for every size.
type f64v3 = u64;
impl VectorSize for f64v3 {
const usize DIMS = 3;
}
// end macro
fn example() {
let var: [f64; 3] = [0.0, 1.0, 2.0];
imul_vn_fl(var, 0.5);
// ...
}
【问题讨论】:
-
我没有任何详细信息,但有这个:github.com/fizyk20/generic-array
-
抱歉,类型级常量是一个非常受欢迎但还没有的功能:github.com/rust-lang/rfcs/issues/1038
-
Rust 1.20 引入了类型关联常量,编辑问题以引用类型 关联 常量,而不是类型常量。
-
type f64v3 = u64; impl VectorSize for f64v3 {}— 这将永远无法工作because type aliases do not create new types。您会立即遇到为同一类型多次实现该特征的问题。