一个表示可以进行元组构造的类型的特性

huangapple go评论129阅读模式
英文:

A trait that represents types that can be tuple constructed

问题

我有以下代码,带有我的虚构 `TupleConstructor` 特质:

pub trait Axis {
    const MIN: Self;
    const MAX: Self;
}

pub trait AxisU64: TupleConstructor<u64> {}

impl<T: AxisU64> Axis for T {
    const MIN = Self(u64::MIN);
    const MAX = Self(u64::MAX);
}

pub struct XAxis(u64);
impl AxisU64 for XAxis {}

pub struct YAxis(u64);
impl AxisU64 for YAxis {}

我想为实现了 Axis 特质的每个对象都有常量,但我不知道是否有相应的语法。所有这些信息应该在泛型实例化时在编译时可用。

另一种选择是使用 frominto,但那不是一个 const fn,我不能将它们定义为常量。

英文:

I have the following code, with my bogus TupleConstructor trait:

pub trait Axis {
    const MIN: Self;
    const MAX: Self;
}

pub trait AxisU64: TupleConstructor&lt;u64&gt; {}

impl&lt;T: AxisU64&gt; Axis for T {
    const MIN = Self(u64::MIN);
    const MAX = Self(u64::MAX);
}

pub struct XAxis(u64);
impl AxisU64 for XAxis {}

pub struct YAxis(u64);
impl AxisU64 for YAxis {}

Essentially, I want to have constants for each object that implements the Axis trait, but I don't know if there's a syntax for this. All of this information should be available at compile-time through generics instantiation.

An alternative is to use from or into, but that is not a const fn and I can't make them constants.

答案1

得分: 4

没有办法从类型中通用地获取元组结构体的构造函数。元组结构体不会因为是元组结构体而获得任何特性,比如特质实现。(而且,即使有一个 TupleConstructor 特质,它也只会对具有公共字段的元组结构体可用,而且你不能用它来定义常量,因为特质函数目前不能从常量评估中调用。)

然而,你可以编写一个派生宏(也许可以借助 macro_rules_attribute,因为它是一个简单的模式),来生成带有这两个常量的 Axis 实现。

英文:

There is no way to generically get a tuple struct's constructor from the type. Tuple structs do not gain any characteristics such as trait implementations due to being tuple structs. (Also, even if there was a TupleConstructor trait, it would only be available for tuple structs with public fields, and you wouldn't be able to use it to define constants because trait functions can't currently be called from const evaluation.)

However, you could write a derive macro (perhaps with the help of macro_rules_attribute since it's a simple pattern) that generates Axis implementations with the two constants.

huangapple
  • 本文由 发表于 2023年8月5日 07:37:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839612.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定