Fix ambiguity issues in use of Borrow<T> #509
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There's a big problem with #506 which I missed during both authoring and testing. All of the following work fine:
However the following does not
It fails because
&usize
implement bothBorrow<usize>
andBorrow<&usize>
. And so there are two solution togen_range
's boundwhere B1: Borrow<T>, B2: Borrow<T>
resulting in a disambiguation error. I.e. rustc doesn't know if we wantT=usize
orT=&usize
.Even though
gen_range
also sayswhere T: SampleUniform
, which is only satisfied forT=usize
, that apparently does not help.The problem could be solved by writing
gen_range::<usize, _, _>(&5, &10)
, but that's obviously not something we want to require.This PR instead implements a
SampleBorrow
trait. Which is essentially an exact copy ofBorrow
, except that it's only implemented whereT=SampleUniform
. So&usize
implementsSampleBorrow<usize>
, but notSampleBorrow<&usize>
, resolving the ambiguity.This adds no complexity at callsites. Implementations of
SampleUniform
will have to writeSampleBorrow
instead ofBorrow
, but otherwise will write exactly the same code.It's a bummer that we can't use the standard
Borrow
, but I don't know of any way to solve that.And
SampleBorrow
does give us more flexibility. For example we could enable passing&&5
, or&Box::new(5)
if we wanted (which can sometime occur with iterators). But that'd be a separate PR if so.