在宏中“使用”的正确方法

Proper way to `use` in a macro

我正在尝试编写一个需要 use 一些项目的宏。这适合每个文件使用一次,但我觉得很脏。有没有更好的方法直接引用项目,比如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 ...
    ))
}

您可以 use 特征,或者您可以使用完整路径引用它:

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)
        }
    }
}

有一个中间地带,你 use 模块,但不是特征:

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)
    }
}