rust 井号加中括号是什么?

阅读 5.2k
6 个回答

Attributes

An attribute is metadata applied to some module, crate or item. This metadata can be used to/for:

  • conditional compilation of code
  • set crate name, version and type (binary or library)
  • disable lints (warnings)
  • enable compiler features (macros, glob imports, etc.)
  • link to a foreign library
  • mark functions as unit tests
    mark functions that will be part of a benchmark
  • attribute like macros

Attributes can take arguments with different syntaxes:

   #[attribute = "value"]
   #[attribute(key = "value")]
   #[attribute(value)]

😊 More detail about this:
rust-by-example
the reference

[actix_web::main]

链接:https://docs.rs/actix-web/lat...
Explanation: Marks async function to be executed by Actix system.

Examples

#[actix_web::main]
async fn main() {
    async { println!("Hello world"); }.await
}

[cfg(test)]

链接: https://doc.rust-lang.org/boo...
Explanation: The #[cfg(test)] annotation on the tests module tells Rust to compile and run the test code only when you run cargo test, not when you run cargo build.

Examples

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        let result = 2 + 2;
        assert_eq!(result, 4);
    }
}

这是 Rust,也就是说编译会解析这种标记然后对相应的代码块做处理
比如 #[cfg(test)] 就是告诉 Rust 这块代码是测试用例

这是典型的装饰器, 组合模式, 通过宏, 对你的代码块添加额外的功能, 简化代码.
你可以了解一下 cargo expand, 可以看到宏展开后的实际代码.

新手上路,请多包涵

这是Rust的宏语法。

[actix_web::main]宏是告诉cargo在actix运行时执行的main的函数。

[cfg(test)]宏是告诉cargo这是测试函数,在运行cargo test的时候会运行这个测试函数。

在Rust中,井号#加中括号[]表示宏(macro)的使用。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进