rustrust-rocket

modify hello world in rocket rust to print variable string with the text


I want my "hello world" Rocket API to display hello, {} but everything I try is not working. I have absolutely no idea how to solve the errors I get. Here is my code:


#[macro_use] extern crate rocket;
use std::fmt::format;

#[get("/")]
fn index() -> &str
{
    hello("curlynux")
}

fn hello(blaze: str) ->  str
{
    return format!("hello, {} !", blaze);
}

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

and the error log:

warning: unused import: `std::fmt::format`
 --> src/main.rs:4:5
  |
4 | use std::fmt::format;
  |     ^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

error[E0106]: missing lifetime specifier
 --> src/main.rs:7:15
  |
7 | fn index() -> &str
  |               ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime
  |
7 | fn index() -> &'static str
  |               ~~~~~~~~

For more information about this error, try `rustc --explain E0106`.

Solution

  • The error message says everything about the problem. Read some Rust basics if you don't understand it.

    You have to add your attribute macros. I removed them for testing with the rust playground.

    fn index() -> String {
        hello("curlynux")
    }
    
    fn hello(blaze: &str) -> String {
        format!("hello, {} !", blaze)
    }
    
    fn main() {
        println!("{}", index());
    }