joc*_*ull 5 macros traits rust
我正在尝试编写一个需要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 ...
))
}
Run Code Online (Sandbox Code Playgroud)
您可以使用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)
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,在模块内部,项目路径是相对的,因此您需要使用一定数量的路径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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
有一个中间立场,你可以使用use模块,但不能使用特征:
use std::fmt;
impl fmt::Display for Something {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.count)
}
}
Run Code Online (Sandbox Code Playgroud)
如果您只是担心打字,您可以为该模块命名,但我相信让它太短会使它更难以理解:
use std::fmt as f;
impl f::Display for Something {
fn fmt(&self, f: &mut f::Formatter) -> f::Result {
write!(f, "{}", self.count)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79 次 |
| 最近记录: |