sak
sak

Reputation: 3287

What's the best way to convert from a Vec to a slice of references?

So let's say I have some struct instances in a Vec:

let records: Vec<Foo> = ...;

And I need to use them with a function which takes a slice of references as an argument:

fn my_func(arg: &[&Foo]) { ... }

How can I get a slice of references out of the Vec? I see there is an as_slice method, but this would give me a slice of Foo, not a slice of &Foo.

Upvotes: 2

Views: 887

Answers (1)

at54321
at54321

Reputation: 11728

Calling the iter() method on a vector Vec<T> creates and returns an iterator over &T. Then you can create a Vec<&T> and pass a reference to it to my_func(). Passing &Vec<&T> to a function that expects &[&T] is possible via deref coercion.

Here is an example where I've used u64 instead of Foo, for the sake of simplicity:

fn my_func(arg: &[&u64]) {
    println!("arg = {arg:?}")    
}

fn main() {
    let records: Vec<u64> = vec![77, 33];
    let a: Vec<&u64> = records.iter().collect();
    my_func(&a);
}

Also note that this line:

let a: Vec<&u64> = records.iter().collect();

Could be replaced with any of these:

let a: Vec<_> = records.iter().collect();
let a = records.iter().collect::<Vec<&u64>>();
let a = records.iter().collect::<Vec<_>>();

Upvotes: 3

Related Questions