VP.
VP.

Reputation: 16705

How to get a slice of references from a vector in Rust?

Somewhere in the API I use I have a function which takes &[&A] as argument but I only have a vector of A objects. When I try to use this function with following syntax

pub struct A(pub u64);

fn test(a: &[&A]){}

fn main() {
   let v = vec![A(1), A(2), A(3)];
   let a = &v[..];
   test(a);
}

I have a error:

<anon>:12:9: 12:10 error: mismatched types:
 expected `&[&A]`,
    found `&[A]`
(expected &-ptr,
    found struct `A`) [E0308]

I have made some attempts but without any success:

let a = &v[&..]

and

let a = &v[&A]

How can I make &[&A] from Vec<A>?

Upvotes: 4

Views: 7826

Answers (1)

mcarton
mcarton

Reputation: 30001

Short answer: you can't. These types are not compatible with each other.

What you could do if this is really what the API needs is

test(&v.iter().collect::<Vec<_>>());

But this allocates a new vector. If you are the author of the API, consider changing it: &[&T] is a weird type to work with since you need different owners for the slice and the objects in it. &[T] already has a pass-by-reference semantic of the inner objects.

Upvotes: 11

Related Questions