编译器:rustc 1.71.0-nightly (c609da59d 2023-04-18)

我试着每晚#![feature(try_blocks)]次,用这个:

#![feature(try_blocks)]
fn test_try(input: Option<i32>) {
    let output = try {
        input?
    };

    println!("{:?}", output);
}

但是编译器声称output需要类型注释.完整的错误信息在这里:

error[E0282]: type annotations needed
 --> src/main.rs:3:9
  |
3 |     let output = try {
  |         ^^^^^^
  |
help: consider giving `output` an explicit type
  |
3 |     let output: /* Type */ = try {
  |               ++++++++++++

如果我试了let output: Option<i32> = ...次,一切都很好.

看起来output应该是Option<i32>,但编译器不能推断这一点.

是因为功能不稳定,还是我错过了什么?output可以是Option<i32>以外的任何其他类型吗?

推荐答案

由于推理问题,try_blocks功能大部分不稳定.Try特征(支持try块和?运算符)的设计使其非常灵活,但编译器也很难推断类型.

在STD中,此表达式的结果只能是Option<i32>.但我们可以写一个,因为驱动try块go 糖化的不是它里面?的类型,而是它产生的类型.所以它可以是任何东西,只要它支持?/Option<i32>.例如:

#![feature(try_blocks, try_trait_v2)]

use std::convert::Infallible;
use std::ops::ControlFlow;

#[derive(Debug)]
struct MyFancyType;

impl std::ops::FromResidual<Option<Infallible>> for MyFancyType {
    fn from_residual(_residual: Option<Infallible>) -> Self {
        Self
    }
}

impl std::ops::FromResidual for MyFancyType {
    fn from_residual(_residual: Infallible) -> Self {
        Self
    }
}

impl std::ops::Try for MyFancyType {
    type Output = i32;
    type Residual = Infallible;

    fn from_output(_output: i32) -> Self {
        Self
    }

    fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
        ControlFlow::Continue(0)
    }
}

fn test_try(input: Option<i32>) {
    let output: MyFancyType = try { input? };

    println!("{:?}", output);
}

Playground.

Rust相关问答推荐

在Rust中创建可变片段的可变片段的最有效方法是什么?

如何初始化match声明中的两个变量而不会激怒borrow 判断器?

重新导出proc宏导致未解决的extern crate错误""

如何在Rust中获得不可辩驳的'if let'模式警告Mutex锁定?""

在没有引用计数或互斥锁的情况下,可以从Rust回调函数内的封闭作用域访问变量吗?

为什么std repeat trait绑定在impl块和关联函数之间?

在Rust中,Box:ed struct 与普通 struct 在删除顺序上有区别吗?

将一个泛型类型转换为另一个泛型类型

在复制类型中使用std::ptr::WRITE_VILAR进行内部可变性的安全性(即没有UnSafeCell)

如何将生存期参数添加到框<>;具有dyn类型别名

如何将带有嵌套borrow /NLL 的 Rust 代码提取到函数中

Rust 如何返回大类型(优化前)?

Rust 程序中的内存泄漏

如何在 Rust 中按 char 对字符串向量进行排序?

如何在 Emacs Elisp 中获得类似格式化的 LSP?

哪些特征通过 `Deref` 而哪些不通过?

在 Rust 中如何将值推送到枚举 struct 内的 vec?

为什么具有 Vec 变体的枚举没有内存开销?

TinyVec 如何与 Vec 大小相同?

覆盖类型的要求到底是什么?为什么单个元素元组满足它?