Fabien
Fabien

Reputation: 13456

How can I declare a &[&T]] in rust?

I have this code I cannot compile :

let vec1 = [1i, 2i, 3i];
let vec2 = [4i, 5i];
let v: &[&[int]] = [&vec1, &vec2];

What I want here is clear : I want to indicate v contains &[int] items, i.e. references to arrays of heterogenous sizes. But, no matter how I tag v's type, I get compiler errors. The above states

tst.rs:8:29: 8:34 error: mismatched types: expected `&[int, ..3]`, found `&[int, ..2]`     (expected array, found array)
tst.rs:8    let v: &[&[int]] = [&vec1, &vec2];
                                       ^~~~~
tst.rs:8:21: 8:35 error: mismatched types: expected `&[&[int]]`, found `[&[int, ..3], ..2]` (expected &-ptr, found array)
tst.rs:8    let v: &[&[int]] = [&vec1, &vec2];
                               ^~~~~~~~~~~~~~

What is the solution here ?

Upvotes: 1

Views: 85

Answers (1)

Francis Gagné
Francis Gagné

Reputation: 65937

let vec1 = [1i, 2i, 3i];
let vec2 = [4i, 5i];
let v = [vec1.as_slice(), vec2.as_slice()];
let v: &[&[int]] = v.as_slice();

The first v is of type [&[int], ..2] and the second v is of type &[&[int]]. We can't define v of type &[&[int]] directly because we must define storage for the [&[int], ..2] before we can borrow it.

Upvotes: 2

Related Questions