Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rust高级特性 #202

Open
vislee opened this issue Mar 15, 2024 · 0 comments
Open

rust高级特性 #202

vislee opened this issue Mar 15, 2024 · 0 comments

Comments

@vislee
Copy link
Owner

vislee commented Mar 15, 2024

rust中以!结尾的函数基本都是宏,例如: print! vec!等。
使用 macro_rules!声明(Declarative)宏,和 三种 过程(Procedural)宏:

  • 自定义 #[derive] 宏在结构体和枚举上指定通过 derive 属性添加的代码
  • 类属性(Attribute-like)宏定义可用于任意项的自定义属性
  • 类函数宏看起来像函数不过作用于作为参数传递的 token

声明宏

下面是vec!的简单定义和说明:

#[macro_export]        // 表明只要导入了定义这个宏的 crate,该宏就应该是可用的。
macro_rules! vec {     //  macro_rules! 和宏名称开始宏定义
    ( $( $x:expr ),* ) => {    // 分支模式() => {}   $( $x:expr )  $()宏变量。 $x:expr是表达式,其匹配 Rust 的任意表达式,并将该表达式命名为 $x。
    // $() 之后的逗号说明一个可有可无的逗号分隔符可以出现在 $() 所匹配的代码之后。紧随逗号之后的 * 说明该模式匹配零个或更多个 * 之前的任何模式。
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push($x);
            )*
            temp_vec
        }
    };
}

vec![1,2,3]展开为:

{
    let mut temp_vec = Vec::new();
    temp_vec.push(1);
    temp_vec.push(2);
    temp_vec.push(3);
    temp_vec
}

定义一个test!可以生成常量,类似于reqwest中StatusCode中的宏status_codes!

struct Test(u32);

macro_rules! test {
    (
        $(
            ($num:expr, $konst:ident);
        )+
    ) => {
        impl Test {
        $(
            pub const $konst: Test = Test($num);
        )+

        }

        fn get(num: u32) -> Option<u32> {
            Some(num)
        }
    }
}

test!{
    (4, FOUR);
    (6, SIX);
}

impl Test {
    pub fn get(self) -> Option<u32> {
        println!("==pub get:===");
        return get(self.0);
    }
}

fn main() {
    let t = Test::SIX;
    println!("=={}   {}", t.get().unwrap(), Test::FOUR.get().unwrap());
}

调用C语言库

目录结构:
cargo new test

├── Cargo.toml
├── absx.c
├── build.rs
├── src
 │   └── main.rs

在Cargo.toml文件添加:

[dependencies]
cc = "1.0.90"

[build-dependencies]
cc = "1.0.90"

build.rs

fn main() {
    cc::Build::new()
        .file("absx.c")
        .compile("absx");
}

absx.c文件:

#include <stdio.h>

int absx(int input) {
    if (input < 0) {
        return -input;
    } else {
        return input * 2;
    }
}

src/main.rs

extern "C" {
    fn absx(input: i32) -> i32;
}

fn main() {
    let result = unsafe { absx(5) };
    println!("The absolute value of 5 is: {}", result);
}

// 链接到 C 库
#[link(name = "absx")]
extern {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant