Is it possible to declare arrays without an explic

2019-08-01 19:27发布

问题:

This question already has an answer here:

  • Can array lengths be inferred in Rust? 1 answer

In Rust, you can declare an array with a specific size:

struct Vector(f64, f64);

fn main() {
    let points: [Vector; 3] = [
        Vector(1.0, 1.0), 
        Vector(5.0, 5.0), 
        Vector(0.0, 0.0),
    ];

    println!("Length is {}\n", points.len());
}

Is there a way to have the length (3 in this case) be implicit, since 3 elements are inside the array. Similar to how in C you can do:

typedef double Vector[2];
Vector points[] = {{1, 1}, {5, 5}, {0, 0}};
printf("Length is %d\n", sizeof(*points) / sizeof(points));

Note that this is an absolute beginner question.

回答1:

As of Rust 1.10 the answer is No, based on a quick series of tests:

let points              = [ ... ]; // OK
let points: [_     ; 3] = [ ... ]; // OK
let points: [Vector; _] = [ ... ]; // REJECTED
let points: [Vector; 3] = [ ... ]; // OK

In Rust, _ is the simple way to ask the compiler to fill in the blanks for you. Unfortunately, it is not accepted instead of 3: the compiler complains rather harshly that it expects an expression.

This is maybe not too surprising as arrays are a special-case at the moment: Rust generics do not allow working with non-type generic parameters yet, so the compiler "hacks" in place for arrays are understandably limited.

For the curious, the exact error is:

error: expected expression, found `_`
 --> <anon>:4:21
4 |>     let points: [_; _] = [
  |>  

Note: and now to wait for someone else to prove me wrong :)



标签: arrays rust