我试图让一个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);
}
我知道你只是想创建一个小例子..但这里的特点是使用很没用。稍微改变你的例子,我[见过这种技术在一些代码库中使用](https://play.rust-lang.org/?gist=2ae7e995af81de014bd8a59971021649&version=stable&backtrace=0)。 –
@SimonWhitehead我不确定你的代码应该达到什么程度。它根本不接受不同数量的参数,并且由于某种原因它创建了第二种类型而不是枚举。 – JelteF
其目的是为了演示enum_的使用,以此来“超载”函数。您可以使用枚举变体将不同数量的参数传入该函数。所以它通过使用枚举作为“超载”机制来翻转你的例子 - 我只是用一个结构作为例子来强调我的例子中的枚举是主要部分。 –