当前位置:网站首页>【Rust 笔记】10-操作符重载
【Rust 笔记】10-操作符重载
2022-07-03 08:24:00 【phial03】
10 - 操作符重载
操作符重载:让自己定义的类型支持算术和其他操作。
支持操作符重载的特型:
类别 特型 操作符 一元操作符 std::ops::Negstd::ops::Not-x!x算术操作符 std::ops::Addstd::ops::Substd::ops::Mulstd::ops::Divstd::ops::Remx + yx - yx * yx / yx % y位操作符 std::ops::BitAndstd::ops::BitOrstd::ops::BitXorstd::ops::Shlstd::ops::Shrx & yx - yx * yx / yx % y复合赋值算术操作符 std::ops::AddAssignstd::ops::SubAssignstd::ops::MulAssignstd::ops::DivAssignstd::ops::RemAssignx += yx -= yx *= yx /= yx %= y复合赋值位操作符 std::ops::BitAndAssignstd::ops::BitOrAssignstd::ops::BitXorAssingstd::ops::ShlAssignstd::ops::ShrAssignx &= y
`x比较 std::cmp::PartialEqstd::cmp::PartialOrdx == y、x != yx < y、x <= y、x > y、x >= y索引 std::ops::Indexstd::ops::IndexMutx[y]、&x[y]x[y] = z、&mut x[y]
10.1 - 算术与位操作符
10.1.1 - 一元操作符
*引用操作符std::ops::Neg特型:实现一元取反操作符-。trait Neg { type Output; fn neg(self) -> Self::Output; }std::ops::Not特型:实现一元非操作符!。trait Not { type Output; fn not(self) -> Self::Output; }对复数值取反的泛型实现:
use std::ops::Neg; impl<T, O> Neg for Complex<T> where T: Neg<Output=O> { type Output = Complex<O>; fn neg(self) -> Complex<O> { Complex { re: -self.re; im: -self.im } } }
10.1.2 - 二元操作符
Rust 的所有数值类型都实现了算术操作符;
Rust 的整数类型和
bool实现了位操作符。它们也实现了接受对这些类型的引用作为一个或两个操作数的逻辑。
算术操作符和位操作符的特型都有统一的形式:
// 针对^操作符的std::ops::BitXor的定义 trait BitXor<RHS=Self> { type Output; fn bitxor(self, rhs: RHS) -> Self::Output; }使用
+操作符可以将一个String和一个&st切片或另一个String拼接起来。但是 Rust 不允许+的左操作数是&str,目的是阻止通过重复小的左操作数来构建长字符串。(会造成性能隐患:所需时间与最终字符串长度的平方成正相关)要一段一段的拼接字符串,最好使用
write!。
10.1.3 - 复合赋值操作符
Rust 的所有数值类型都实现了算术复合赋值操作符;
Rust 的整数类型和
bool还实现了位复合赋值操作符。对
Complex类型进行AddAssign的泛型实现:use std::ops::AddAssign; impl<T> AddAssign for Complex<T> where T: AddAssign<T> { fn add_assign(&mut self, rhs: Complex<T>) { self.re += rhs.re; self.im += rhs.im; } }复合操作符的内置特型与对应的二元操作符的内置特型相互独立。
实现
std::ops::Add不会自动实现std::ops::AddAssign。如果要让自定义类型作为+=操作符的左操作数,那么必须实现AddAssign。与二元特型
Shl和Shr类似,ShlAssign和ShrAssign特型:没有将RHS类型参数默认为Self,所以实现时必须明确给出右操作数的类型。
10.2 - 相等测试
==和!=是对调用std::cmp::PartialEq特型方法eq和ne的简写:assert_eq!(x == y, x.eq(&y)); assert_eq!(x != y, x.ne(&y));std::cmp::PartialEq的定义:trait PartialEq<Rhs: ?Sized = Self> { fn eq(&self, other: &Rhs) -> bool; fn ne(&self, other: &Rhs) -> bool { !self.eq(other) } }Complex的完整实现:impl<T: PartialEq> PartialEq for Complex<T> { fn eq(&self, other: &Complex<T>) -> bool { self.re == other.re && self.im == other.im } }Rhs: ?Sized放宽了 Rust 对类型参数必须有大小的限制,以支持PartialEq<str>或PartialEq<T>这样的特型。方法eq和ne接收&Rhs类型的参数,可以比较&str和&[T]。标准库将
Eq定义为PartialEq的扩展,且没有定义新方法:trait Eq: PartialEq<Self> { }为
Complex类型实现Eq:impl<T: Eq> Eq for Complex<T> { }在
Complex类型定义的derive属性中包含Eq也可以实现:#[derive(Clone, Copy, Debug, Eq, PartialEq)] struct Complex<T> { ... }
10.3 - 顺序比较
Rust 通过特型 std::cmp::PartialOrd 规定了顺序比较操作符 <、>、<= 和 >= 的行为:
trait PartialOrd<Rhs = Self>: PartialEq<Rhs> where Rhs: ?Sized {
fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
fn lt(&self, other: &Rhs) -> bool {
... }
fn le(&self, other: &Rhs) -> bool {
... }
fn gt(&self, other: &Rhs) -> bool {
... }
fn ge(&self, other: &Rhs) -> bool {
... }
}
10.4-Index 与 IndexMut
通过实现
std::ops::Index和std::ops::IndexMut特型,可以对相应类型使用类似a[i]这样的索引表达式。trait Index<Idx> { type Output: ?Sized; fn index(&self, index: Idx) -> &Self::Output; } trait IndexMut<Idx>: Index<Idx> { fn index_mut(&mut self, index: Idx) -> &mut Self::Output; }a[i..j]是下述表达式的简写:*a.index(std::ops::Range { start: i, end: j })
10.5 - 其他操作符
*val 解引用操作符和. 调用方法的点操作符,可以使用 Deref 和 DerefMut 特型来重载。
下述操作符都不支持重载:
- 错误检查操作符
?只能用于Result值; - 逻辑操作符
&&和||仅限于布尔值; ..操作符只能用于创建Range值;&操作符只能借用引用;=操作符只能转移或复制值。f(x)函数调用操作符不支持重载,如果要一个可调用的值,通常写一个闭包就可以了。
详见《Rust 程序设计》(吉姆 - 布兰迪、贾森 - 奥伦多夫著,李松峰译)第十二章
原文地址
边栏推荐
- Unity Editor Extension - event handling
- Some understandings of 3dfiles
- About the problem that the editor and the white screen of the login interface cannot be found after the location of unityhub is changed
- Dotween plug-in
- KunlunBase MeetUP 等您来!
- Basic operation and process control 2
- C#课程设计之学生教务管理系统
- Golang url的编码和解码
- Unity learning notes
- 使用base64编码传图片
猜你喜欢

Base64 and base64url

Introduction to Base64 coding

KunlunBase MeetUP 等您来!

Use of ue5 QRcode plug-in

Unity editor expansion - controls, layouts

Un système de gestion de centre commercial pour la conception de cours de technologie d'application de base de données

Thymeleaf 404 reports an error: there was unexpected error (type=not found, status=404)

ArrayList

Notes on understanding applets 2022/7/3

C course design employee information management system
随机推荐
Compilation error: "not in executable format: file format not recognized"“
Student educational administration management system of C # curriculum design
Classes and objects
MySQL 8
796 · unlock
UE4 call DLL
Unity editor expansion - scrolling list
Encoding and decoding of golang URL
Use of ue5 QRcode plug-in
Intersectionpicker in osgearth
Clion toolchains are not configured configure disable profile problem solving
C language - Introduction - essence Edition - take you into programming (I)
About Wireshark's unsuccessful installation of npcap
Three characteristics
100 GIS practical application cases (78) - Multi compliance database design and data warehousing
Easy touch plug-in
[audio and video] ijkplayer error code
P1596 [USACO10OCT]Lake Counting S
Simply start with the essence and principle of SOM neural network
详解sizeof、strlen、指针和数组等组合题