Pearl for `Vec<A> -> &[&A]`

I have an owned Vec<A>, but I need a &[&A]. Getting to &[A] is easy enough with as_slice(), but how do I make the next step?

Please and thanks.

You can collect into a new Vec:

vec.iter().collect::<Vec<&_>>().as_ref()
1 Like

&[A] is a reference to a continous slice of memory where the A elemets is put side by side, while &[&A] is a reference to a slice of references (pointers). So the memory layout is different, and it cannot be done without copying. But if you iterate over a &[A], you get &A items anyway; since you don't own the A:s, you can only borrow the items.

So my may not need to do anything at all, but of it really is needed, you may do something like.

myvec = vec![one, other, third];
myrefs = myvec.iter().collect::<Vec<_>>();
myrefref: &[&A] = &myrefs;
1 Like

Thanks guys, that did it.

I don't know the context feeling here, but my gut feeling is "don't". Would it be feasible to change the interface such that it works with Iterator<Item=&A> or [impl AsRef<A>], rather than with &[&A]?

An &[&A] is a bit of an redundant type, as it forces double indirection.

2 Likes

Unfortunately I'm calling a library function with the result, I don't have control over the type requirements.

out of curiosity, which library is that?

1 Like

Thanks!

Yeah, the reason why that API works like this is that it's a method of an object safe trait, and there isn't a strictly better way to encode that (AsRef/Iterator require generics, and break object safety). Practically, I'd probably changed that to use just a Vec<A> for this specific case (well to (A, Vec<A>) to enforce the non-empty constraint of the API), just to keep things simple.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.