gpt4 book ai didi

error-handling - rust Snafu crate : no method named `fail` found for enum `Error` in the current scope

转载 作者:行者123 更新时间:2023-12-03 11:38:07 30 4
gpt4 key购买 nike

我正在尝试使用Snafu条板箱进行一些基本的错误处理。在这种情况下,我尝试在给Error而不是check_value()的情况下返回CustomInputValue::CiFloat。根据我在docs的this页面上的示例中看到的内容,我认为这会起作用:

use snafu::{Backtrace, ResultExt, Snafu, ensure};

#[derive(Debug, Snafu)]
pub enum Error{
#[snafu(display("Incorrect Type: {:?}"), kind)]
IncorrectInputType{kind: CustomInputValue},
}

#[derive(Debug, Clone, PartialEq)]
pub enum CustomInputValue{
CiBool(bool),
CiInt(i32),
CiFloat(f64),
}

type Result<T, E = Error> = std::result::Result<T, E>;

fn main(){
check_value(CustomInputValue::CiFloat(10.0));
}

fn check_value(val: CustomInputValue )->Result<()>{
match val {
CustomInputValue::CiFloat(inp)=>inp,
_=>Error::IncorrectInputType{kind: val}.fail()?
};
Ok(())
}
但是,这会产生错误:
error[E0599]: no method named `fail` found for enum `Error` in the current scope
--> src/main.rs:24:57
|
4 | pub enum Error{
| -------------- method `fail` not found for this
...
24 | _=>Error::IncorrectInputType{kind: val}.fail()?
| ^^^^ method not found in `Error`
是什么导致此错误?我需要实现故障功能吗?我在文档中的任何地方都看不到为 fail()编写的自定义 Error函数,并且在文档中找不到需要 fail()Error函数的任何东西。

最佳答案

#[derive(Snafu)]属性为每个枚举变量创建“上下文选择器”。这意味着Error::IncorrectInputType引用了该变体,而IncorrectInputType是具有fail()方法的生成的结构。
解决方法是使用此选择器而不是枚举:

match val {
CustomInputValue::CiFloat(inp) => inp,
_ => IncorrectInputType { kind: val }.fail()?
// ^^^^^^^^^^^^^^^^^^ no Error::
};
您可以浏览 SNAFU user's guide的其余部分以了解有关宏的更多信息。

另外, kind属性中的 #[snafu(display(...))]放错了位置。它应该是显示部分中的参数:
#[snafu(display("Incorrect Type: {:?}", kind))]
IncorrectInputType { kind: CustomInputValue },

关于error-handling - rust Snafu crate : no method named `fail` found for enum `Error` in the current scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66058836/

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