Trait 未实现(实现 trait 的东西) [英] Trait not implemented for (thing that implements trait)

查看:57
本文介绍了Trait 未实现(实现 trait 的东西)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我想,Rust 正试图告诉我一个谎言,但也许我只是疯了......

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

那里的 where 子句应该表明 R 肯定 实现了 Rng,否则......好吧,来吧,对吧?但是当我尝试编译它时,它上下发誓 rng 没有实现 rand::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.

到底是什么?

rustc 1.0.0-nightly (cfea8ec41 2015-03-10)(建于 2015-03-11)(以防万一)

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)
                    ^~~~~~~~~~~~~~~~~~~~

我将突出显示类型为 &mut R.您的问题源于您引用了太多参考资料.你的 rng 是一个 &mut R.您正在然后在调用ind_sample 时尝试对它进行另一个引用.这将创建一个 &mut &mut R,它没有实现 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() {}

这篇关于Trait 未实现(实现 trait 的东西)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆