【问题标题】:How to use a type (ty) within a macro to construct a struct instance in Rust?如何在宏中使用类型(ty)在 Rust 中构造结构实例?
【发布时间】:2016-12-30 06:15:08
【问题描述】:

在宏中使用ty 时,这几乎适用于我尝试过的所有情况。 但是,它似乎不能用于声明新的struct 实例。

例如:$my_type { some_member: some_value }

一个更全面的例子

macro_rules! generic_impl {
    ($my_type:ty) => {
        impl $rect_ty {
            pub fn flip(&self) -> $my_type { self.some_method() }
            pub fn swap(&self, &other: $my_type) -> { self.some_swap_method(other) }
            // so far so good!

            // now our troubles start :(
            pub fn create(&self) -> $my_type {
                return $my_type { foo: 1, bar: 2, baz: 2 };
                //     ^^^^^^^^ this fails!!!
            }
        }
    }
}

// example use
generic_impl(MyStruct);
generic_impl(MyOtherStruct);

错误是:

error: expected expression, found `MyStruct`

ty 更改为expr 意味着我不能使用impl $my_type

除了传入 2x 参数之外,一个是 ty,另一个是 expr

有没有办法根据宏的 ty 参数构造结构?

【问题讨论】:

    标签: macros rust


    【解决方案1】:

    不,不是ty

    简单的解决方法是捕获ident,这在两种情况下都有效。如果您需要比简单标识符更复杂的东西,那么您可能需要分别捕获名称(用于构造)和类型(用于其他用途)并在使用时指定它们。

    【讨论】:

      猜你喜欢
      • 2019-09-24
      • 2022-01-15
      • 1970-01-01
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      相关资源
      最近更新 更多