Trait not implemented for (thing that implements t

2019-09-20 04:19发布

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)

标签: rust traits
1条回答
仙女界的扛把子
2楼-- · 2019-09-20 04:48

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() {}
查看更多
登录 后发表回答