【发布时间】:2018-08-24 09:37:39
【问题描述】:
我正在尝试获取随机数生成器。由于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? 的副本,因为另一个问题是关于 如何 从函数返回特征,而这个问题是关于 为什么 编译器不允许我返回特征,但希望我返回不是函数返回类型的OsRng。
【问题讨论】:
标签: rust traits return-type