英文:
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
特质的每个对象都有常量,但我不知道是否有相应的语法。所有这些信息应该在泛型实例化时在编译时可用。
另一种选择是使用 from
或 into
,但那不是一个 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<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 {}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论