Trait not implemented for (thing that implements trait)

随声附和 提交于 2019-12-13 10:19:20

问题


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)


回答1:


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() {}


来源:https://stackoverflow.com/questions/28999104/trait-not-implemented-for-thing-that-implements-trait

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!