【发布时间】:2017-02-14 21:03:19
【问题描述】:
我正在尝试使用一个带有一个和两个参数的new 构造函数,但我似乎无法弄清楚如何做到这一点。目前这是否可能?
我现在得到的错误是多个适用项目在范围内 (playground)
trait __Constructor1<T> {
fn new(T) -> Self;
}
trait __Constructor2<T, U> {
fn new(T, U) -> Self;
}
enum MixedInts {
SmallInt(i32),
TwoSmallInts(i32, i32),
}
impl __Constructor1<i32> for MixedInts {
fn new(__0: i32) -> MixedInts {
MixedInts::SmallInt(__0)
}
}
impl __Constructor2<i32, i32> for MixedInts {
fn new(__0: i32, __1: i32) -> MixedInts {
MixedInts::TwoSmallInts(__0, __1)
}
}
fn main() {
let x = MixedInts::new(2i32);
let y = MixedInts::new(2i32, 2i32);
}
【问题讨论】:
-
我知道您只是尝试创建一个小示例.. 但是这里的 trait 用法非常无用。稍微改变一下你的例子,我have seen this technique used in a few codebases。
-
@SimonWhitehead 我不确定您的代码应该实现什么。它根本不接受不同数量的参数,并且由于某种原因它创建了第二种类型而不是枚举。
-
目的是演示使用枚举作为“重载”函数的一种方式。您可以使用枚举变体将不同数量的参数传递给函数。因此,它通过使用枚举作为“重载”机制来翻转您的示例 - 我只是使用结构作为示例来强调我示例中的枚举是主要部分。
标签: rust