Rust 编程视频教程(进阶)——029_2 声明宏

视频地址

头条地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/

源码地址

github地址:https://github.com/anonymousGiga/learn_rus...

讲解内容

使用marco_rules!的声明宏
例子1:

let v = vec![1, 2, 3];//vec!就是用marco_rules!的声明宏

例子2:
(1)mkdir learn_marco1
(2)cd learn_marco1
(3)vim Cargo.toml,编辑工作空间:

[workspace]
members = [
    "mac",
    "main",
]

(4)cargo new mac –lib
(5)编辑mac/src/lib.rs:

#[macro_export]
macro_rules! my_vec {
    ( $( $x:expr ),* ) => {
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push($x);
            )*
            temp_vec
        }
    };
}

(6)cargo new main
(7)编辑main/Cargo.toml添加:

[dependencies]
mac = {path = "../mac"}

(8)编辑main/src/main.rs如下:

use mac;
fn main() {
    let v = mac::my_vec![1, 2, 3];
    println!("v = {:?}", v);
    println!("Hello, world!");
}

说明:在上面的例子中定义了声明宏,并在main中进行使用。宏中的代码等价于如下

let mut temp_vec = Vec::new();
temp_vec.push(1);
temp_vec.push(2);
temp_vec.push(3);
temp_vec
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
120
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商