Rust 宏魔法之默认参数

该博客展示了如何使用Rust语言创建一个名为`requests`的宏,用于构建HTTP请求。宏通过匹配表达式来设置URL、请求方法和超时时间,并将它们转换为适当的数据类型。在主函数中,宏被调用并打印出配置的请求参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

use std::any::Any;


macro_rules! requests{
    (
        $($key:expr=> $value:expr);*
        $(;)?
    ) => {
        let mut url: Box<dyn Any> = Box::new("");
        let mut method: Box<dyn Any> = Box::new("");
        let mut timeout: Box<dyn Any> = Box::new(0);

        $(
        match $key {
            "url" => {
                url = Box::new($value);
            },
            "method" => {
                method = Box::new($value);
            },
            "timeout" => {
                timeout = Box::new($value);
            },
            _ => {
                panic!("Error key: {:?}", $key);
            }
        }
        )*

        let mut url: &str = url.downcast_ref::<&str>().unwrap();
        let mut method: &str = method.downcast_ref::<&str>().unwrap();
        let mut timeout: u64 = *timeout.downcast_ref::<i32>().unwrap() as u64;

        println!("url-> {}", url);
        println!("method-> {}", method);
        println!("timeout-> {}", timeout);
    }
}


fn main() {
    requests! {
        "url"=> "https://www.baidu.com/";
        "method"=> "GET";
        "timeout"=> 10;
    };
}

Out:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值