【作业打卡】Week6. 模块六:Rust 内容扩展(选学) #32
bonnie0519
started this conversation in
Assignment/Tasks
Replies: 1 comment
1. 尝试编写一个声明宏和一个过程宏,体验它们的异同1)声明宏是用 macro_rules! repeat {
($block:expr; $n:expr) => {
{
let mut i = 0;
while i < $n {
$block;
i += 1;
}
}
};
}
fn main() {
repeat!({
println!("Hello, world!");
}; 5);
}2)过程宏是编译时插件,用于在编译阶段对 Rust 代码进行转换。过程宏可以分为三种类型:派生宏、属性宏和自定义宏。下面是一个简单的示例,展示如何使用过程宏来自动生成 use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
// 解析输入的 Rust 代码
let ast = parse_macro_input!(input as DeriveInput);
// 生成要插入的 Rust 代码片段
let expanded = quote! {
impl HelloMacro for #name {
fn hello_macro() {
println!("Hello, Macro! My name is {}", stringify!(#name));
}
}
};
// 输出转换后的 Rust 代码
TokenStream::from(expanded)
}2. 结合你过去的编码经验,你是怎么理解 Rust 中的不安全问题的,安全问题有被扩大吗?1)在Rust语言中, |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
All reactions