#Convert Vec<Item> to Vec<&Item>

28 messages · Page 1 of 1 (latest)

ancient hedge
#

I have an Iterator that iterates over &&Arc<Mutex<Chunk>> and need to convert it to Vec<&Chunk>. Any Idea how I can accomplish that?

The reason behind this issue is that I have a lot of functions that take Vec<&Chunk>. I am upgrading my app and trying to use mutlpile threads and so on so I wrapped them in a Mutex. Lazy me does not want to change all function signatures to accept MutexGuard.

lost trout
#

that's a lot of references ferrisHmm

#

you need two steps:

  • Collect it into a Vec<MutexGuard<Chunk>>
  • Transform that into Vec<&Chunk>
ancient hedge
lost trout
#

something like

let guards: Vec<_> = iter().map(|x| x.lock().unwrap()).collect();
let refs: Vec<&Chunk> = guards.iter().map(|x| &*x).collect();
ancient hedge
lost trout
#

i really thought deref coercion would work here

#

then you gotta deref manually

#
let guards: Vec<_> = iter().map(|x| x.lock().unwrap()).collect();
let refs: Vec<&Chunk> = guards.iter().map(|x| x.deref()).collect();
#

oh it's because of iter

#

this should also work

let guards: Vec<_> = iter().map(|x| x.lock().unwrap()).collect();
let refs: Vec<&Chunk> = guards.iter().map(|x| &**x).collect();
#

maybe even

let guards: Vec<_> = iter().map(|x| x.lock().unwrap()).collect();
let refs: Vec<&Chunk> = guards.iter().map(|x| *x).collect();
ancient hedge
lost trout
#

* is the deref operator, it turns the &MutexGuard into a MutexGuard. which would normally be invalid, but it's not moved yet.
then the second one turns the MutexGuard into a Chunk, which is ofc also not valid, but it's not moved yet.
then the & takes a reference to the Chunk, so it doesn't get moved.
It's really weird and I don't like it, so I usually use .deref() instead which is much cleaner IMO

ancient hedge
magic ether
#

It's for anything that implements Deref

north swan
#

Is there a reason you use Vec<&Chunk> rather than &[Chunk]?

ancient hedge
north swan
#

But why do you take &[&Chunk] rather than just &[Chunk]?

ancient hedge
#

Wouldnt I move the Chunk there?

north swan
#

No, it's like taking a reference to multiple Chunks at once. If your chunks aren't contiguous (i.e. aren't all next to each other in an array or vec), then yes you'd need to clone/move them, but that seems unlikely.

ancient hedge
magic ether
#

I mean, you'd need to change it to Arc<Mutex<Vec<Chunk>>> probably.

magic ether
#

I'm not really sure what's being suggested, actually

north swan
#

I'm confused why you're ending up with a ton of individual Arc<Mutex<Chunk>>s, especially if you're then working with them in bulk.

lost trout
#

I don't think it's unreasonable to work with them both in bulk and individually in the same code base