macros - 宏中 `use` 的正确方法

标签 macros rust traits

我正在尝试编写一个需要使用一些项目的宏。这适合每个文件使用一次,但我觉得很脏。有没有更好的方法直接引用项目,比如 impl std::ops::Add for $t 之类的?谢谢!

#[macro_export]
macro_rules! implement_measurement {
    ($($t:ty)*) => ($(
        // TODO: Find a better way to reference these...
        use std::ops::{Add,Sub,Div,Mul};
        use std::cmp::{Eq, PartialEq};
        use std::cmp::{PartialOrd, Ordering};

        impl Add for $t {
            type Output = Self;

            fn add(self, rhs: Self) -> Self {
                Self::from_base_units(self.get_base_units() + rhs.get_base_units())
            }
        }

        impl Sub for $t {
            type Output = Self;

            fn sub(self, rhs: Self) -> Self {
                Self::from_base_units(self.get_base_units() - rhs.get_base_units())
            }
        }

        // ... others ...
    ))
}

最佳答案

您可以使用 trait,也可以使用完整路径引用它:

struct Something {
    count: i8,
}

impl std::fmt::Display for Something {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.count)
    }
}

请注意,在模块内部,项路径是相对,因此您需要使用一些super 或绝对路径(我认为更好的选择):

mod inner {
    struct Something {
        count: i8,
    }

    impl ::std::fmt::Display for Something {
        fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
            write!(f, "{}", self.count)
        }
    }
}

有一个中间地带,您可以使用模块,但不使用 trait:

use std::fmt;

impl fmt::Display for Something {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.count)
    }
}

如果你只是担心打字,你可以别名模块,但我认为让它太短会更难理解:

use std::fmt as f;

impl f::Display for Something {
    fn fmt(&self, f: &mut f::Formatter) -> f::Result {
        write!(f, "{}", self.count)
    }
}

关于macros - 宏中 `use` 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31092336/

相关文章:

docker - 版本 `GLIBC_2.29' 未找到

rust - 结构内部的模式匹配

visual-studio-code - 是否有用于从选定代码或剪贴板代码创建新文件的 VS 代码快捷方式?

c++ - 某些宏语句在 C++ 中可能会产生意想不到的结果?

c - 宏三元逗号表达式用作语句时会导致警告

rust - 为什么 impl trait 不能用于返回多个/条件类型?

visual-c++ - 是否可以防止在 Visual C++ 中删除带有空 __VA_ARGS__ 的逗号?

groovy - 使用 Groovy 特征编写 Geb 页面

Python(Enthought)元组/列表特征 : how to access a specific element?

generics - 如何从盒装特征对象获取对结构的引用?