首页 > 其他分享 >Rust 2

Rust 2

时间:2023-03-12 19:57:00浏览次数:39  
标签:code macro macros println Hello Rust

This is the source code of the traditional Hello World program.

// This is a comment, and is ignored by the compiler.
// You can test this code by clicking the "Run" button over there ->
// or if you prefer to use your keyboard, you can use the "Ctrl + Enter"
// shortcut.

// This code is editable, feel free to hack it!
// You can always return to the original code by clicking the "Reset" button ->

// This is the main function.
fn main() {
    // Statements here are executed when the compiled binary is called.

    // Print text to the console.
    println!("Hello World!");
}

macro_rules!
Rust provides a powerful macro system that allows metaprogramming. As you've seen in previous chapters, macros look like functions, except that their name ends with a bang !, but instead of generating a function call, macros are expanded into source code that gets compiled with the rest of the program. However, unlike macros in C and other languages, Rust macros are expanded into abstract syntax trees, rather than string preprocessing, so you don't get unexpected precedence bugs.

Macros are created using the macro_rules! macro.

// This is a simple macro named `say_hello`.
macro_rules! say_hello {
    // `()` indicates that the macro takes no argument.
    () => {
        // The macro will expand into the contents of this block.
        println!("Hello!");
    };
}

fn main() {
    // This call will expand into `println!("Hello");`
    say_hello!()
}

说白了,宏就是Rust里的类似Lambda的一个接口,因为很明显用到Java中的
或Ts中的() => { }表达式。

So why are macros useful?

Don't repeat yourself. There are many cases where you may need similar functionality in multiple places but with different types. Often, writing a macro is a useful way to avoid repeating code. (More on this later)
Domain-specific languages. Macros allow you to define special syntax for a specific purpose. (More on this later)
Variadic interfaces. Sometimes you want to define an interface that takes a variable number of arguments. An example is println! which could take any number of arguments, depending on the format string. (More on this later)

实际上DRY原则也不仅仅是宏带来的吧?比如接口方法或者公有类一样可以带来不同,
那么究竟Rust的宏和Java中的函数式接口、接口以及其他语言中的通用工具类中的静
态方法,区别在哪里?
留下一个疑问,留到下一章节。

标签:code,macro,macros,println,Hello,Rust
From: https://www.cnblogs.com/ukzq/p/17208908.html

相关文章