我想得到一个随机数发生器.由于OsRng::new()
可能会失败,如果必须的话,我想回到thread_rng()
:
extern crate rand; // 0.5.5
use rand::{thread_rng, OsRng, RngCore};
fn rng() -> impl RngCore
{
match OsRng::new() {
Ok(rng) => rng,
Err(e) => thread_rng()
}
}
但是,我收到了我无法理解的错误信息:
error[E0308]: match arms have incompatible types
--> src/lib.rs:6:5
|
6 | / match OsRng::new() {
7 | | Ok(rng) => rng,
8 | | Err(e) => thread_rng(),
| | ------------ match arm with an incompatible type
9 | | }
| |_____^ expected struct `rand::OsRng`, found struct `rand::ThreadRng`
|
= note: expected type `rand::OsRng`
found type `rand::ThreadRng`
为什么编译器在这里期望rand::OsRng
而不是RngCore
的实现?如果我删除match
并直接返回thread_rng()
,我不会得到上面的错误消息.
我不相信这是How do I return an instance of a trait from a method?的复制品,因为另一个问题是关于how,一个人可以从函数返回一个特征,这个问题是关于why,编译器不允许我返回一个特征,但希望我返回一个OsRng
,它不是函数的返回类型.