How to return a String created in the code? #2693
-
While experimenting with Rocket I tried to send back a generated string. #[macro_use]
extern crate rocket;
#[get("/")]
fn index() -> &'static str {
let answer = 42;
format!("The answer is {}", answer)
//format!("The answer is {}", answer).as_str()
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
} I got an error: expected `&str`, found `String` I tried to call
I could use a Template, but I wonder if there is a way to send back a string. I could also define the return to be #[macro_use]
extern crate rocket;
#[get("/")]
fn index() -> String {
let count = 42;
format!("The answer is {}", count)
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
} |
Beta Was this translation helpful? Give feedback.
Answered by
SergioBenitez
Jan 5, 2024
Replies: 1 comment
-
No, that's perfectly correct. You cannot return a reference to something that heap allocated on the outgoing frame; that would be a dangling pointer. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
SergioBenitez
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No, that's perfectly correct. You cannot return a reference to something that heap allocated on the outgoing frame; that would be a dangling pointer.