#[macro_use]
extern crate failure;
use actix_web::{error, http, HttpResponse};
#[derive(Fail, Debug)]
enum UserError {
#[fail(display = "Validation error on field: {}", field)]
ValidationError { field: String },
}
impl error::ResponseError for UserError {
fn error_response(&self) -> HttpResponse {
match *self {
UserError::ValidationError { .. } =>
HttpResponse::new(http::StatusCode::BAD_REQUEST),
}
}
}
这是什么意思{ .. }
这里?
这是一个pattern-matching destructuring wildcard,允许一个并不需要指定对象的所有成员。在这种情况下:
UserError::ValidationError { .. }
这已经够了那个match
分支枚举变种ValidationError
,无论其内容(在这种情况下field
):
enum UserError {
#[fail(display = "Validation error on field: {}", field)]
ValidationError { field: String },
}
这也是有用的,当一个只与物体的一些成员担心;考虑Foo
结构包含baz
和bar
领域:
struct Foo {
bar: usize,
baz: usize,
}
如果你只在baz
有兴趣,你可以写:
fn main() {
let x = Foo { bar: 0, baz: 1 };
match x {
Foo { baz, .. } => println!("{}", baz), // prints 1
_ => (),
}
}