简体   繁体   English

使用特征和泛型函数在rust中重载函数是否有不利之处?

[英]Is there any downside to overloading functions in rust using a trait & generic function?

I find this is particularly useful pattern to allow method overloading: 我发现这对于允许方法重载特别有用:

struct Foo {
  value:uint
}

trait HasUIntValue {
  fn as_uint(self) -> uint;
}

impl Foo {
  fn add<T:HasUIntValue>(&mut self, value:T) {
    self.value += value.as_uint();
  }
}

impl HasUIntValue for int {
  fn as_uint(self) -> uint {
    return self as uint;
  }
}

impl HasUIntValue for f64 {
  fn as_uint(self) -> uint {
    return self as uint;
  }
}

#[test]
fn test_add_with_int()
{
  let mut x = Foo { value: 10 };
  x.add(10i);
  assert!(x.value == 20);
}

#[test]
fn test_add_with_float()
{
  let mut x = Foo { value: 10 };
  x.add(10.0f64);
  assert!(x.value == 20);
}

Is there any meaningful downside to doing this? 这样做有什么有意义的缺点吗?

There is at least one downside: it cannot be an afterthought. 至少有一个缺点:这不可能是事后的想法。

In C++, ad-hoc overloading allows you to overload a function over which you have no control (think 3rd party), whereas in Rust this is not actually doable. 在C ++中,临时重载允许您重载一个您无法控制的函数(请考虑第三方),而在Rust中,这实际上是不可行的。

That being said, ad-hoc overloading is mostly useful in C++ because of ad-hoc templates, which is the only place where you cannot know in advance which function the call will ultimately resolve to. 就是说,由于ad-hoc模板,临时重载在C ++中最有用,这是您无法预先知道调用最终将解析为哪个函数的唯一位置。 In Rust, since templates are bound by traits, the fact that overloading cannot be an afterthought is not an issue since only the traits functions can be called anyway. 在Rust中,由于模板受特征约束,所以重载不能成为事后考虑的事实并不是问题,因为无论如何只能调用特征函数。

No, there is no downside; 不,没有缺点。 this is exactly the pattern to implement overloading in Rust. 这正是在Rust中实现重载的模式。

There are a number of types in the standard library which do exactly this. 标准库中有许多类型可以做到这一点。 For example, there is BytesContainer trait in path module, which is implemented for various kinds of strings and vectors. 例如, 路径模块中有BytesContainer特征,该特征是为各种字符串和向量实现的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM