Explicitly stating the type of vector length for r

2019-08-04 12:42发布

I'm trying to get my head around Rust and I'm being faced with a probably obvious error.

I have found a method which computes the dot product of two vectors and I want to implement it so that I do not need to consume the vectors to do so. Right now it looks like the following:

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
    }

The problem occurs in the first line of the function body: the compiler cannot infer the type of u.len() as u is a reference.

How can I work around this? Is it possible to explicitly state the type?

标签: rust
1条回答
聊天终结者
2楼-- · 2019-08-04 13:17

The problem as stated does not exist. The error the above code produces is:

<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

&u: Vec<f32> cannot work; this says that u should be bound to the contents of a pointer... which is impossible given the parameter is of type Vec<f32>. I suspect you meant to say u: &Vec<f32>.

But you shouldn't do that, either. There's effectively no reason to ever pass a &Vec<_> when you can just pass a &[_] instead, which will work for more types. So what you really want is u: &[f32].

Once you fix both arguments, the code compiles with no errors.

查看更多
登录 后发表回答