赋值运算符不能在 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