rustrust-rocket

Why am I getting "mismatched types" error from Rocket example code?


I just copied the code from the Rocket documentation (here and here) 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();
}
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?


Solution

  • 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:

    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
    

    Either you want to return a String type or switch the return type to be nothing:

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