英文:
What does returning `_` mean in Rust?
问题
#[launch]
fn rocket() -> _ {
rocket::build()
.attach(json::stage())
.attach(msgpack::stage())
.attach(uuid::stage())
}
英文:
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())
}
答案1
得分: 6
#[launch]
宏在这里试图变得聪明。文档中写道:
为了避免在常见情况下需要导入任何项,launch 属性将推断一个写作
_
的返回类型为Rocket<Build>
:
因此,这只是宏提供的一种简写,用于避免指定返回类型。
通常情况下,当在类型的位置使用 _
时,它是编译器根据上下文来推断的占位符。然而,在返回类型中不允许这样做,因为 Rust 要求函数签名必须明确。在 playground 上查看错误 here on the playground。属性宏通常要求它们所修饰的项必须是有效的 Rust,但使用 _
仍然在语法上有效(尽管在语义上无效),因此是允许的。
英文:
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.
答案2
得分: 3
这通常不是有效的Rust代码。#[launch]
属性运行一个宏,该宏会转换其注释的函数,以支持这种语法。
这种语法意味着函数的返回类型应该从函数体中推断出来。
参见:
英文:
This is not usually valid Rust. The #[launch]
attribute runs a macro which transforms the function that it annotates, adding support for this syntax.
The syntax means that the return type of the function should be inferred from the function's body.
See:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论