简体   繁体   中英

Trait not implemented for (thing that implements trait)

So, Rust is trying to tell me a fib, I think, but maybe I'm just out of my mind...

fn get_random<T, R>(range: Range<T>, rng: &mut R) -> T
    where T: SampleRange + PartialOrd,
          R: Rng
{
    range.ind_sample(&mut rng)
}

The where clause there should indicate that R definitely implements Rng, otherwise... Well, come on, right? But when I try to compile this, it swears up and down that rng does not implement rand::Rng.

What on earth?

rustc 1.0.0-nightly (cfea8ec41 2015-03-10) (built 2015-03-11) (in case you were wondering)

Here's the actual error generated:

<anon>:10:11: 10:31 error: the trait `rand::Rng` is not implemented for the type `&mut R` [E0277]
<anon>:10     range.ind_sample(&mut rng)
                    ^~~~~~~~~~~~~~~~~~~~

I'll highlight for the type &mut R . Your issue stems from the fact that you are taking too many references. Your rng is a &mut R . You are then trying to take another reference to it when calling ind_sample . This would create a &mut &mut R , which doesn't implement Rng .

use std::rand::distributions::range::SampleRange;
use std::rand::Rng;
use std::rand::distributions::Range;
use std::rand::distributions::IndependentSample;

 fn get_random<T, R>(range: Range<T>, rng: &mut R) -> T
    where T: SampleRange + PartialOrd,
          R: Rng
{
    range.ind_sample(rng)
}

fn main() {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM