rust - 有没有办法覆盖 Rust 类型的赋值运算符?

标签 rust operator-overloading

这个问题在这里已经有了答案:





How can I overload the assignment operation in Rust?

(1 个回答)


2年前关闭。




我的问题如下:我想建立一个类似原始的结构,其值范围更有限。如在

#[repr(transparent)]
struct MyLimitedInt {
  v: i8,
}

但确保 v的值始终在 -10 之间和 10 .我知道我可以实现std::ops特征以检查加法等的值,但似乎没有一种方法可以构造 MyLimitedInt 的实例以类似原始的方式,同时仍然检查边界(如 let my_v: MyLimitedInt = -12; ,它应该将值限制为 -10 )。

在类 C 语言中,我可以通过覆盖类型的 = 来做到这一点。运算符,但是有没有办法在 Rust 中实现类似的结果,而不需要更详细的构造函数或 setter ?

最佳答案

赋值运算符不能在 Rust 中重载。但是,您可以重载其他运算符或改用方法 - 例如:

use std::cmp::{min, max};

#[repr(transparent)]
struct MyLimitedInt {
  v: i8,
}

impl MyLimitedInt {
  pun fn from_clamped(value: i8) -> Self {
    Self { v: min(10, max(value, -10))
  }

  /// Sets the value of the int, constraining it to the range [-10, 10]
  pub fn set_clamped(&mut self, value: i8) {
    *self = Self::from_clamped(value);
  }
}

这可以通过算术运算符的重载进行扩展,使其更像原语一样可用:
use std::ops::Add;

impl Add for MyLimitedInt {
  type Output = Self;

  fn add(self, other: Self) -> Self {
    Self::from_clamped(self.value + other.value)
  }
}

impl Add<i32> for MyLimitedInt {
  type Output = Self;

  fn add(self, other: i32) -> Self {
    Self::from_clamped(self.value + other.value)
  }
}

这将使加法运算符与 MyLimitedInt 一起使用成为可能。 ,自动钳制结果:
let x = MyLimitedInt::from_clamped(20) + 5; // 10
let y = MyLimitedInt::from_clamped(-20) + x; // 0

关于rust - 有没有办法覆盖 Rust 类型的赋值运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60951515/

相关文章:

c++ - 方括号重载运算符以设置而不是获取 C++

C++:*(乘)运算符的结合性不是从左到右

rust - 在bufreader.lines()的for循环后无法使用移动的BufReader

rust - 将 std::cmp::Reverse 与 binary_search_by_key 结合使用

console - 在原始模式下使用 termion 时如何创建新行?

c++ - 在哪里释放函数重载运算符中分配的内存

c++ - 具有重载类型转换运算符的函数对象崩溃

concurrency - rust future -cpupool : inconsistent behavior explanations

rust - Rust 宏在特征定义中起作用吗?

C++ 重载运算符同时作为成员和函数?