我正试图让我的头围绕Rust,我正面临一个可能明显的错误.
我找到了一个计算两个向量的点积的方法,我想实现它,这样我就不需要使用向量来实现它.现在它看起来如下:
pub fn dot(&u: Vec<f32>, &v: Vec<f32>) -> f32 {
let len = cmp::min(u.len(), v.len());
let mut xs = &u[..len];
let mut ys = &v[..len];
let mut s = 0.;
let (mut p0, mut p1, mut p2, mut p3, mut p4, mut p5, mut p6, mut p7) =
(0., 0., 0., 0., 0., 0., 0., 0.);
while xs.len() >= 8 {
p0 += xs[0] * ys[0];
p1 += xs[1] * ys[1];
p2 += xs[2] * ys[2];
p3 += xs[3] * ys[3];
p4 += xs[4] * ys[4];
p5 += xs[5] * ys[5];
p6 += xs[6] * ys[6];
p7 += xs[7] * ys[7];
xs = &xs[8..];
ys = &ys[8..];
}
s += p0 + p4;
s += p1 + p5;
s += p2 + p6;
s += p3 + p7;
for i in 0..xs.len() {
s += xs[i] * ys[i];
}
s
}
Run Code Online (Sandbox Code Playgroud)
问题出现在函数体的第一行:编译器无法推断出u.len()作为u引用的类型.
我该如何解决这个问题?是否可以明确说明类型?
所述问题不存在.上面代码产生的错误是:
<anon>:3:16: 3:18 error: mismatched types:
expected `collections::vec::Vec<f32>`,
found `&_`
(expected struct `collections::vec::Vec`,
found &-ptr) [E0308]
<anon>:3 pub fn dot(&u: Vec<f32>, &v: Vec<f32>) -> f32 {
^~
<anon>:3:16: 3:18 help: see the detailed explanation for E0308
Run Code Online (Sandbox Code Playgroud)
&u: Vec<f32>不能工作; 这表示u应该绑定到指针的内容......如果参数是类型,这是不可能的Vec<f32>.我怀疑你是想说的u: &Vec<f32>.
但是,你不应该这样做,无论是.有效有没有理由永远传递&Vec<_>时,你可以通过一个&[_]代替,这会为更多类型的工作.所以你真正想要的是u: &[f32].
一旦修复了两个参数,代码就会编译而没有错误.