【问题标题】:Macro that makes struct based on struct field's types基于结构字段类型创建结构的宏
【发布时间】:2020-08-26 02:29:45
【问题描述】:

我正在尝试制作一个宏来生成具有新函数实现的结构。新函数需要根据字段的类型调用函数,并将返回值作为字段值。

新的实现最终应该像这样工作:

struct foo {
    test: i32,
    other: String,
}

impl foo {
    fn new() -> Self {
        foo {
           test: get_i32(),
           other: get_string(),
        }
    }
}

这是我当前的代码:

macro_rules! test {
    (struct $name:ident { $($fname:ident : $ftype:ty),* }) => {
        #[derive(Debug)]
        pub struct $name {
            $(pub $fname : $ftype),*
        }

        impl $name {
            fn new(mut v: Vec<u8>) -> Self {
                $name {
                    $($fname : ),*
                }
            }
        }
    };
}

我尝试过添加匹配语句,但它给出了不兼容的武器类型错误。

impl $name {
    fn new(mut v: Vec<u8>) -> Self {
        $name {
            $($fname : match &stringify!($ftype)[..] {
                "i32" => get_i32(),
                "String" => get_string(),
            }),*
        }
    }
}

谢谢。

【问题讨论】:

  • 您尝试放置匹配语句;你能告诉我们你尝试了什么吗?现在很难说出你的问题到底是什么。
  • @Frxstrem 我添加了我尝试进行匹配的方式,但它给出了错误:“match arm 的类型不兼容”和“预期 i32,找到结构 std::string::String”。跨度>

标签: rust rust-macros


【解决方案1】:

我设法使用另一个返回 any 的函数来让它工作。

macro_rules! test {
    (struct $name:ident { $($fname:ident : $ftype:ty),* }) => {
        #[derive(Debug)]
        pub struct $name {
            $(pub $fname : $ftype),*
        }

        impl $name {
            fn new(mut v: Vec<u8>) -> Self {
                $name {
                    $($fname : get_feild::<$ftype>(stringify!($ftype)).downcast_ref::<$ftype>().unwrap().clone()),*
                }
            }
        }
    };
}

fn get_feild<T>(t: &str) -> Box<dyn std::any::Any> {
    match t {
        "i32" => Box::new(get_i32()),
        "String" => Box::new(get_string()),
        _ => panic!("UNKNOWN TYPE"),
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 2018-10-05
    • 2017-10-07
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    相关资源
    最近更新 更多