Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vector

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>?

like image 383
Victor Polevoy Avatar asked Oct 29 '25 07:10

Victor Polevoy


1 Answers

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.

like image 74
mcarton Avatar answered Oct 30 '25 22:10

mcarton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!