问题描述
我正在尝试使用一个和两个参数的 new
构造函数,但我似乎无法弄清楚如何做到这一点.目前这可能吗?
I'm trying to have a new
constructor with one and with two arguments, but I can't seem to figure out how to do this. Is this even possible at the moment?
我现在的错误是多个适用项目在范围内(游乐场)
What I have now gives me an error that multiple applicable items are in scope (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);
}
推荐答案
Rust 不支持重载的函数/方法.作为一种解决方法,您可以使用元组在单个参数中接收多个值.然后,您可以定义一个 trait 并为该单个参数的可接受类型实现它,该函数将简单地委托给 trait 的实现.
Rust doesn't support overloaded functions/methods. As a workaround, you can use tuples to receive multiple values in a single argument. You can then define a trait and implement it for the admissible types of that single argument, and the function will simply delegate to the trait's implementation.
enum MixedInts {
SmallInt(i32),
TwoSmallInts(i32, i32),
}
trait IntoMixedInts {
fn into(self) -> MixedInts;
}
impl MixedInts {
fn new<A>(args: A) -> MixedInts
where A: IntoMixedInts
{
args.into()
}
}
impl IntoMixedInts for i32 {
fn into(self) -> MixedInts {
MixedInts::SmallInt(self)
}
}
impl IntoMixedInts for (i32, i32) {
fn into(self) -> MixedInts {
MixedInts::TwoSmallInts(self.0, self.1)
}
}
fn main() {
let x = MixedInts::new(2i32);
let y = MixedInts::new((2i32, 2i32));
}
注意:在这个例子中,你可以使用标准的 From
和 Into
trait,而不是定义你自己的 trait.但是,由于一致性规则(确保对于特定类型只能存在特定特征的一个实现的规则),它可能不适用于其他特征.
Note: In this example, you could use the standard From
and Into
traits instead of defining your own trait. It might not work for other traits, though, due to the coherence rules (the rules that ensure that there can only exist one implementation of a certain trait for a certain type).
enum MixedInts {
SmallInt(i32),
TwoSmallInts(i32, i32),
}
impl MixedInts {
fn new<A>(args: A) -> MixedInts
where A: Into<MixedInts>
{
args.into()
}
}
impl From<i32> for MixedInts {
fn from(a: i32) -> MixedInts {
MixedInts::SmallInt(a)
}
}
impl From<(i32, i32)> for MixedInts {
fn from((a, b): (i32, i32)) -> MixedInts {
MixedInts::TwoSmallInts(a, b)
}
}
fn main() {
let x = MixedInts::new(2i32);
let y = MixedInts::new((2i32, 2i32));
}
这篇关于是否可以重载具有不同数量参数的函数(使用特征)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!