Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 取随机数的模时类型推断失败_Rust - Fatal编程技术网

Rust 取随机数的模时类型推断失败

Rust 取随机数的模时类型推断失败,rust,Rust,rustc 1.0.0-每晚(be9bd7c93 2015-04-05)(2015-04-05年建成) 这段代码在Rust beta版之前编译过,但现在没有: src/main.rs:8:10: 8:22 error: unable to infer enough type information about `_`; type annotations required [E0282] src/main.rs:8 test(rand::random() % 20)

rustc 1.0.0-每晚(be9bd7c93 2015-04-05)(2015-04-05年建成)

这段代码在Rust beta版之前编译过,但现在没有:

src/main.rs:8:10: 8:22 error: unable to infer enough type information about `_`; type annotations required [E0282]
src/main.rs:8     test(rand::random() % 20)
                       ^~~~~~~~~~~~
我必须编写以下代码来编译:

extern crate rand;

fn test(a: isize) {
    println!("{}", a);
}

fn main() {
    test(rand::random::<isize>() % 20)
}
extern板条箱兰德;
fn测试(a:isize){
println!(“{}”,a);
}
fn main(){
测试(随机::()%20)
}

如何让编译器推断类型?

在这种情况下,编译器无法推断类型,因为未知因素太多

让我们调用
R
的输出类型
rand::random()
,调用
I
的类型
20

测试(rand::random()%20)
施加的条件仅为:

R: Rand + Rem<I, Ouput=isize>
I: integral variable (i8, u8, i16, u16, i32, u32, i64, u64, isize or usize)
R:Rand+Rem
I:积分变量(i8、u8、i16、u16、i32、u32、i64、u64、isize或usize)
没有任何东西可以保证只有一对
(T,I)
能够满足这些要求(实际上创建一个新类型
T
来满足这些要求非常容易),因此编译器无法自行选择


因此,在这里使用
rand::random::()
是正确的方法。

在这种情况下,编译器无法推断类型,因为有太多的未知数

让我们调用
R
的输出类型
rand::random()
,调用
I
的类型
20

测试(rand::random()%20)
施加的条件仅为:

R: Rand + Rem<I, Ouput=isize>
I: integral variable (i8, u8, i16, u16, i32, u32, i64, u64, isize or usize)
R:Rand+Rem
I:积分变量(i8、u8、i16、u16、i32、u32、i64、u64、isize或usize)
没有任何东西可以保证只有一对
(T,I)
能够满足这些要求(实际上创建一个新类型
T
来满足这些要求非常容易),因此编译器无法自行选择


因此,在这里使用
rand::random::()
是正确的方法。

还请注意,您不应该使用
random()
然后使用
%20
来获取介于
0
20
之间的数字,而是使用
rand::distributions::Range
(参见示例)。使用模算子的问题是,你不能得到真正的随机分布。相反,您增加了小数字的概率。还要注意,您不应该使用
random()
然后使用
%20
来获取介于
0
20
之间的数字,而是使用
rand::distributions::Range
(参见示例)。使用模算子的问题是,你不能得到真正的随机分布。而是增加了小数字的概率。