简体   繁体   中英

What does { .. } mean in a pattern?

I found the following piece of code in the doc about actix :

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

What does { .. } mean here?

It's a pattern-matching destructuring wildcard that allows one to not need to specify all the members of an object. In this case:

UserError::ValidationError { .. }

It is enough for that match branch that the enum variant is ValidationError , regardless of its contents (in this case field ):

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

It is also useful when one is concerned only with some members of an object; consider a Foo struct containing baz and bar fields:

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

If you were only interested in baz , you could write:

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

    match x {
        Foo { baz, .. } => println!("{}", baz), // prints 1
        _ => (),
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM