gpt4 book ai didi

rust - 为什么 impl trait 不能用于返回多个/条件类型?

转载 作者:行者123 更新时间:2023-11-29 08:19:43 26 4
gpt4 key购买 nike

我正在尝试获取随机数生成器。由于 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

最佳答案

impl Trait不等同于返回接口(interface)或基类对象。这是一种表达“我不想写我要返回的特定类型的名称”的方式。您仍然返回一个单一的特定类型的值;你只是没有说哪种类型。

这些分支中的每一个都返回不同的类型,因此出现了问题。实现相同的特征是不够的。

在这种特定情况下,您可能需要的是像 Box<dyn RngCore> 这样的特征对象。 .

extern crate rand; // 0.6.5

use rand::{rngs::OsRng, thread_rng, RngCore};

fn rng() -> Box<dyn RngCore> {
match OsRng::new() {
Ok(rng) => Box::new(rng),
Err(_) => Box::new(thread_rng()),
}
}

注意:如果您使用的是稍旧版本的 Rust,您可能需要删除 dyn关键词。它在之前的 (2015) 版本的 Rust 中是可选的。

关于rust - 为什么 impl trait 不能用于返回多个/条件类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58596644/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com