H. *_*ane 0 syntax pattern-matching rust
#[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),
}
}
}
Run Code Online (Sandbox Code Playgroud)
{ .. }这里的意思是什么?
它是一种模式匹配的解构通配符,允许用户不需要指定对象的所有成员.在这种情况下:
UserError::ValidationError { .. }
Run Code Online (Sandbox Code Playgroud)
对于该match分支而言,enum变体就足够了ValidationError,无论其内容如何(在本例中field):
enum UserError {
#[fail(display = "Validation error on field: {}", field)]
ValidationError { field: String },
}
Run Code Online (Sandbox Code Playgroud)
当一个人只关心某个对象的某些成员时,它也很有用; 考虑Foo包含baz和bar字段的结构:
struct Foo {
bar: usize,
baz: usize,
}
Run Code Online (Sandbox Code Playgroud)
如果您只对此感兴趣baz,可以写:
fn main() {
let x = Foo { bar: 0, baz: 1 };
match x {
Foo { baz, .. } => println!("{}", baz), // prints 1
_ => (),
}
}
Run Code Online (Sandbox Code Playgroud)