简体   繁体   中英

Rust Rocket mismatched types

I just copied the example from rocket docs and have error.

  #![feature(proc_macro_hygiene, decl_macro)]

  #[macro_use]
  extern crate rocket;

  #[get("/person/<name>?<age>")]
  fn person(name: String, age: u8) -> String {
      let mike = uri!(person: "Mike Smith", 28);

      assert_eq!(mike.to_string(), "/person/Mike%20Smith?age=28");
  }

  fn main() {
      rocket::ignite().mount("/", routes![person]).launch();
  }

Error Message:

main.rs|7 col 37 error| mismatched types expected struct `std::string::String`, found () note: expected type `std::string::String` found type `()` [E0308]                         
main.rs|7 col 4 info| mismatched types implicitly returns `()` as its body has no tail or `return` expression note: expected type `std::string::String` found type `()` [E0308]

Why copying from an example give me error?

And it's my first post :hurray:

It's complaining because you have a return type specified, and not returning it. When I ran this code the compiler gave a more helpful answer, and something that you should include next time in your question:

$> cargo run
. . .
error[E0308]: mismatched types
 --> src/main.rs:7:37
  |
7 | fn person(name: String, age: u8) -> String {
  |    ------                           ^^^^^^ expected struct `std::string::String`, found `()`
  |    |
  |    implicitly returns `()` as its body has no tail or `return` expression

error: aborting due to previous error

Either you want to return a String type, or swtich the return type to a function:

#[get("/person/<name>?<age>")]
fn person(name: String, age: u8) -> () {
    let mike = uri!(person: "Mike Smith", 28);
    assert_eq!(mike.to_string(), "/person/Mike%20Smith?age=28");

    // or leave the return type as string, but return a string
    //return name
}

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