gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:51:37 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com