Search code examples
rustrust-rocket

What does returning `_` mean in Rust?


I'm a newbie in rust lang. What does returning -> _ mean for the rocket function?

#[launch]
fn rocket() -> _ {
    rocket::build()
        .attach(json::stage())
        .attach(msgpack::stage())
        .attach(uuid::stage())
}

Solution

  • The #[launch] macro is trying to be clever here. The documentation reads:

    To avoid needing to import any items in the common case, the launch attribute will infer a return type written as _ as Rocket<Build>:

    So its just a shorthand provided by the macro to avoid specifying that return type.

    Normally when a _ is used in place of a type, it is a placeholder for the compiler to infer it based on context. However, this is not allowed for return types since Rust requires function signatures to be explicit. See the error here on the playground. Attribute macros usually require the item they're decorated on to be valid Rust, but using _ is still syntactically valid (even though its not semantically valid) so it is allowed.