Skip to content

Implementing SliceRandom::choose_multiple(_weighted) is impossible if you aren't simply forwarding the calls to an inner [T] #1307

Closed
@LikeLakers2

Description

@LikeLakers2

Hi! I'm trying to implement rand::seq::SliceRandom for a custom Vec-like collection I'm building. However, I found myself stuck in trying to implement SliceRandom::choose_multiple.

The collection is set up as follows:

pub struct PaletteVec<T> {
	palette: ::indexset::IndexSet<T>,
	
	// Vec of indices into `self.palette`
	items: Vec<usize>,
}

Getting a T from this collection involves mapping a usize obtained from self.items, to a T obtained from self.palette. In most cases, I can use Iterator::map or Option::map for this.

However, SliceRandom::choose_multiple and SliceRandom::choose_multiple_weighted require me to return a rand::seq::SliceChooseIter. I do not see a way to construct this on my own - the only way to make one is via self.items.choose_multiple(), which would return a usize rather than a T - and I especially do not see a way to implement this such that it maps the usizes to Ts before returning values.

Because I can't return a SliceChooseIter, I can't implement SliceRandom - not unless I decide to put unimplemented!() in the methods that return a SliceChooseIter. This feels like a deficiency in the rand crate, one that I'm unsure how to solve - but I'm also wondering if there's a way around it that I'm unaware of.

So, any help with this, please? Or is this something that would require rand to change how SliceRandom is implemented?

Metadata

Metadata

Assignees

No one assigned

    Labels

    E-easyParticipation: easy job

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions