Rust编程的一些语法规则!

Rust与erlang一样,什么样的语句后面需要或不需要分号,都有不好言说的特点,这些特点,

编译器会告诉你,比如下面的语句,IF的Ok/Err都是匹配到Result, 此时不需要加分号!

pub fn myinfo(email: &str, pool: &web::Data<Pool>) -> Result<User, ServiceError> {
    if let Ok(user) = User::find_user_by_email(&email,  &pool.get().unwrap()) {
         Ok(user)
    } else {
         Err(ServiceError::new(StatusCode::INTERNAL_SERVER_ERROR, constants::MESSAGE_PROCESS_TOKEN_ERROR.to_string()))
    }

下面的写法也没有问题(Ok/Err后面的分号是可以去掉的):

pub fn myinfo(email: &str, pool: &web::Data<Pool>) -> Result<User, ServiceError> {
    if let Ok(user) = User::find_user_by_email(&email,  &pool.get().unwrap()) {
         return Ok(user);
    } else {
         return Err(ServiceError::new(StatusCode::INTERNAL_SERVER_ERROR, constants::MESSAGE_PROCESS_TOKEN_ERROR.to_string()));
    }

但为了代码的简洁,用第一种方法即可!

下面的代码,第个match语句的ok前必需加return:

pub fn myinfo(req: HttpRequest, pool: web::Data<Pool>) -> impl Future<Item = HttpResponse, Error = Error> {
    info!("{:?}",req);
    match req.headers().get("email") {
        Some(email) => {
            match account_service::myinfo(email.to_str().unwrap(), &pool) {
                Err(e) => error!("{:?}", e),
                Ok(user) => return ok(HttpResponse::Ok().json(ResponseBody::new(constants::MESSAGE_OK, user))),
            }},
        None => ()
    }
    ok(HttpResponse::BadRequest().json(ResponseBody::new(constants::MESSAGE_TOKEN_MISSING, constants::EMPTY)))
}

因为return是直接将数据返回,这是一个Future的结构体,如果不加return, 则是返回给外层的match, 而外层

的match需要的是一个(), 如None返回的那样,这时就会产生一个编译错误!

error[E0308]: match arms have incompatible types
  --> src/api/account_controller.rs:76:29
   |
74 | /             match account_service::myinfo(email.to_str().unwrap(), &pool) {
75 | |                 Err(e) => error!("{:?}", e),
   | |                           ----------------- this is found to be of type `()`
76 | |                 Ok(user) => ok(HttpResponse::Ok().json(ResponseBody::new(constants::MESSAGE_OK, user))),
   | |                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected (), found struct `futures::Done`
77 | |             }},
   | |_____________- `match` arms have incompatible types
   |
   = note: expected type `()`
              found type `futures::Done<actix_web::HttpResponse, _>`
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

 

Tags

添加新评论

Restricted HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。