[英]How Do I pass object “std::rand::task_rng()” to a function in Rust?
I have a test program where I need to generate a random number. 我有一个测试程序,需要生成一个随机数。 I therefore did a test comparing using
因此,我做了一个测试,比较使用
"uVal = rand::task_rng().gen();"
each time a random number is generated compared to creating an object using eg. 每次生成一个随机数,与使用例如创建对象相比,生成一个随机数。 :
:
let mut oRandom = std::rand::task_rng()
and generating multiple random numbers. 并生成多个随机数。 Using the object (oRandom) created is much faster, so I thought I should pass the object to the function generating the random number, however I haven't been able to find a way to do that.
使用创建的对象(oRandom)的速度要快得多,所以我认为我应该将该对象传递给生成随机数的函数,但是我找不到找到这种方法的方法。 It's not critical, but I presume it can be done.
这并不重要,但我想可以做到。
Example 1 : not using the object : (much slower than 2) 示例1:不使用对象:(比2慢得多)
let mut uVal : u8;
for _ in range(1, iMax) {
uVal = std::rand::task_rng().gen();
Example 2 : using the object : (much faster than 1) 示例2:使用对象:(比1快得多)
let mut oRandom = std::rand::task_rng();
let mut uVal : u8;
for _ in range(1, iMax) {
uVal = oRandom.gen();
Example 3 : my attempt to pass the object to the function : 例3:我试图将对象传递给函数:
12 let mut oRandom = std::rand::task_rng();
13 fTest03(iMax, &mut oRandom);
53 fn fTest03(iMax : i64, oRandom : &mut std::rand::task_rng) {
This results in the following error :
test_rand003.rs:53:38: 53:57 error: use of undeclared type name
`std::rand::task_rng`
test_rand003.rs:53 fn fTest03(iMax : i64, oRandom : &mut std::rand::task_rng) {
How can I pass the variable "oRandom" in line 13 above to a function? 如何将上面第13行中的变量“ oRandom”传递给函数?
There are two ways, either one can use the generic method, so it works with other RNGs, if you decide to stop using the task-local one: 有两种方法,任何一种都可以使用通用方法,因此,如果您决定停止使用任务本地方法,则它可以与其他RNG一起使用:
fn fTest03<R: Rng>(iMax: i64, oRandom: &mut R) { ... }
Or, you can just use the return type of task_rng
directly: 或者,您可以直接使用
task_rng
的返回类型:
fn fTest03(iMax: i64, oRandom: @mut IsaacRng) { ... }
(You may have to import Rng
/ IsaacRng
, or fully-qualify them eg std::rand::Rng
.) (您可能需要导入
Rng
/ IsaacRng
或完全限定它们,例如std::rand::Rng
。)
Either one should work with fTest03(10, std::rand::task_rng())
. 任何一种都应该与
fTest03(10, std::rand::task_rng())
。
task_rng() is not a type, it's a function that returns a task local random number generator (TaskRng). task_rng()不是类型,它是一个返回任务本地随机数生成器(TaskRng)的函数。
The signature of task_rng function is: task_rng函数的签名为:
pub fn task_rng() -> @mut TaskRng
So if you change line 53 to: 因此,如果将第53行更改为:
fn fTest03(iMax : i64, oRandom : &mut std::rand::Rng) {...
things should work nicely. 事情应该很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.