是什么{..}中的模式是什么意思?

问题描述 投票:0回答:1

我发现在约docactix下面的代码:

#[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),
        }
    }
}

这是什么意思{ .. }这里?

syntax rust pattern-matching
1个回答
6
投票

这是一个pattern-matching destructuring wildcard,允许一个并不需要指定对象的所有成员。在这种情况下:

UserError::ValidationError { .. }

这已经够了那个match分支枚举变种ValidationError,无论其内容(在这种情况下field):

enum UserError {
    #[fail(display = "Validation error on field: {}", field)]
    ValidationError { field: String },
}

这也是有用的,当一个只与物体的一些成员担心;考虑Foo结构包含bazbar领域:

struct Foo {
    bar: usize,
    baz: usize,
}

如果你只在baz有兴趣,你可以写:

fn main() {
    let x = Foo { bar: 0, baz: 1 };

    match x {
        Foo { baz, .. } => println!("{}", baz), // prints 1
        _ => (),
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.