Rust 运算符重载
使用 Rust 的 + 运算符和 * 运算符,可以像对任何内置数值类型一样对 Complex 进行加法运算和乘法运算.
z = z * z + c;
你可以让自己的类型支持算术运算符和其他运算符,只要实现一些内置特型即可。这叫作运算符重载,其效果跟 C++、C#、Python 和 Ruby 中的运算符重载很相似。
算术运算符与按位运算符
在 Rust 中,表达式 a + b 实际上是 a.add(b) 的简写形式,也就是对标准库中 std::ops::Add 特型的 add 方法的调用。
附件
运算符重载的特型汇总表
| 类别 | 特型 | 运算符 |
|---|---|---|
| 一元运算符 | std::ops::Negstd::ops::Not |
-x!x |
| 算术运算符 | std::ops::Addstd::ops::Substd::ops::Mulstd::ops::Divstd::ops::Rem |
x + yx - yx * yx / yx % y |
| 按位运算符 | std::ops::BitAndstd::ops::BitOrstd::ops::BitXorstd::ops::Shlstd::ops::Shr |
x & y`x |
| 复合赋值算术运算符 | std::ops::AddAssignstd::ops::SubAssignstd::ops::MulAssignstd::ops::DivAssignstd::ops::RemAssign |
x += yx -= y x *= yx /= yx %= y |
| 复合赋值按位运算符 | std::ops::BitAndAssignstd::ops::BitOrAssignstd::ops::BitXorAssignstd::ops::ShlAssignstd::ops::ShrAssign |
x &= y`x |
| 比较 | std::cmp::PartialEqstd::cmp::PartialOrd |
x == y、x != yx < y、x <= y、x > y、x >= y |
| 索引 | std::ops::Indexstd::ops::IndexMut |
x[y]、&x[y]x[y] = z、&mut x[y] |
评论