[英]Rust Snafu Crate: no method named `fail` found for enum `Error` in the current scope
我正在嘗試使用Snafu crate 進行一些基本的錯誤處理。 在這種情況下,當check_value()
被賦予除CustomInputValue::CiFloat
的任何內容時,我試圖返回一個Error
。 根據我在文檔中此頁面上的示例中看到的內容,我認為這會起作用:
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`
是什么導致了這個錯誤? 我需要實現一個失敗的 function 嗎? 我在文檔中沒有看到這樣的自定義fail()
function 是為Error
編寫的,並且在文檔中找不到任何需要fail()
function 的Error
。
#[derive(Snafu)]
屬性為每個枚舉變體創建“上下文選擇器”。 這意味着Error::IncorrectInputType
指的是變體,而IncorrectInputType
是具有fail()
方法的生成結構。
解決方法是使用此選擇器而不是枚舉:
match val {
CustomInputValue::CiFloat(inp) => inp,
_ => IncorrectInputType { kind: val }.fail()?
// ^^^^^^^^^^^^^^^^^^ no Error::
};
您可以瀏覽SNAFU 用戶指南的 rest 以了解有關宏的更多信息。
此外, #[snafu(display(...))]
屬性中的kind
放錯了位置。 它應該是顯示部分中的一個參數:
#[snafu(display("Incorrect Type: {:?}", kind))]
IncorrectInputType { kind: CustomInputValue },
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.