当前位置:网站首页>[rust note] 10 operator overloading
[rust note] 10 operator overloading
2022-07-03 08:36:00 【phial03】
10 - operators overloading
operators overloading : Let the type you define support arithmetic and other operations .
Special types that support operator overloading :
Category Special type The operator Unary operators std::ops::Negstd::ops::Not-x!xarithmetic operator std::ops::Addstd::ops::Substd::ops::Mulstd::ops::Divstd::ops::Remx + yx - yx * yx / yx % yBit operators std::ops::BitAndstd::ops::BitOrstd::ops::BitXorstd::ops::Shlstd::ops::Shrx & yx - yx * yx / yx % yCompound assignment arithmetic operator std::ops::AddAssignstd::ops::SubAssignstd::ops::MulAssignstd::ops::DivAssignstd::ops::RemAssignx += yx -= yx *= yx /= yx %= yCompound assignment bitwise operator std::ops::BitAndAssignstd::ops::BitOrAssignstd::ops::BitXorAssingstd::ops::ShlAssignstd::ops::ShrAssignx &= y
`xCompare std::cmp::PartialEqstd::cmp::PartialOrdx == y、x != yx < y、x <= y、x > y、x >= yIndexes std::ops::Indexstd::ops::IndexMutx[y]、&x[y]x[y] = z、&mut x[y]
10.1 - Arithmetic and bitwise operators
10.1.1 - Unary operators
*Reference operatorstd::ops::NegSpecial type : Implement the unary negation operator-.trait Neg { type Output; fn neg(self) -> Self::Output; }std::ops::NotSpecial type : Implement unary non operator!.trait Not { type Output; fn not(self) -> Self::Output; }Generic implementation of negation of complex values :
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 - Binary operators
Rust All numeric types of implement arithmetic operators ;
Rust And
boolImplements the bitwise operator .They also implement logic that accepts references to these types as one or two operands .
The special types of arithmetic operators and bit operators have unified forms :
// in the light of ^ Operator std::ops::BitXor The definition of trait BitXor<RHS=Self> { type Output; fn bitxor(self, rhs: RHS) -> Self::Output; }Use
+Operators can put aStringAnd a&stSlice or anotherStringSplice up . however Rust Don't allow+The left operand of is&str, The purpose is to prevent the construction of long strings by repeating small left operands .( Will cause performance hazards : The time required is positively related to the square of the final string length )You need to splice strings one by one , Best use
write!.
10.1.3 - The compound assignment operator
Rust All numeric types of implement arithmetic compound assignment operators ;
Rust And
boolIt also implements the bit compound assignment operator .Yes
ComplexType to proceedAddAssignThe generic implementation of :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; } }The built-in features of the compound operator and the corresponding binary operator are independent of each other .
Realization
std::ops::AddIt doesn't work automaticallystd::ops::AddAssign. If you want a custom type to act as+=The left operand of the operator , Then it must be realizedAddAssign.And binary type
ShlandShrsimilar ,ShlAssignandShrAssignSpecial type : No willRHSThe type parameter defaults toSelf, Therefore, the type of right operand must be clearly given in the implementation .
10.2 - Equality test
==and!=It's a call tostd::cmp::PartialEqSpecial methodeqandneAbbreviation :assert_eq!(x == y, x.eq(&y)); assert_eq!(x != y, x.ne(&y));std::cmp::PartialEqThe definition of :trait PartialEq<Rhs: ?Sized = Self> { fn eq(&self, other: &Rhs) -> bool; fn ne(&self, other: &Rhs) -> bool { !self.eq(other) } }ComplexFull implementation :impl<T: PartialEq> PartialEq for Complex<T> { fn eq(&self, other: &Complex<T>) -> bool { self.re == other.re && self.im == other.im } }Rhs: ?SizedRelaxed Rust There must be size restrictions on type parameters , To support thePartialEq<str>orPartialEq<T>Such a special type . Methodeqandnereceive&RhsParameters of type , You can compare&strand&[T].The standard library will
EqDefined asPartialEqAn extension of , And there is no new method defined :trait Eq: PartialEq<Self> { }by
ComplexType implementationEq:impl<T: Eq> Eq for Complex<T> { }stay
ComplexType definedderiveProperty containsEqIt can also be realized :#[derive(Clone, Copy, Debug, Eq, PartialEq)] struct Complex<T> { ... }
10.3 - Sequence comparison
Rust Pass the special type std::cmp::PartialOrd Specifies the sequential comparison operator <、>、<= and >= act :
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 And IndexMut
By implementing
std::ops::Indexandstd::ops::IndexMutSpecial type , You can use something likea[i]Such an index expression .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]Is the abbreviation of the following expression :*a.index(std::ops::Range { start: i, end: j })
10.5 - Other operators
*val Dereference operators and . Call the point operator of the method , have access to Deref and DerefMut Special type to overload .
The following operators do not support overloading :
- Error checking operator
?It can only be used forResultvalue ; - Logical operators
&&and||Boolean values only ; ..Operators can only be used to createRangevalue ;&Operators can only borrow references ;=Operators can only transfer or copy values .f(x)Function call operators do not support overloading , If you want a callable value , Usually write a closure .
See 《Rust Programming 》( Jim - Brandy 、 Jason, - By orendov , Translated by lisongfeng ) Chapter 12
Original address
边栏推荐
- KunlunBase MeetUP 等您来!
- 【Rust笔记】06-包和模块
- Markdown directory generation
- C#课程设计之员工信息管理系统
- MXone Pro自适应2.0影视模板西瓜视频主题苹果cmsV10模板
- Unity editor expansion - controls, layouts
- Animation_ IK overview
- 基于SSM的校园失物招领平台,源码,数据库脚本,项目导入运行视频教程,论文撰写教程
- UE4 source code reading_ Bone model and animation system_ Animation node
- Get to know unity2 for the first time
猜你喜欢

Creation of osgearth earth files to the earth ------ osgearth rendering engine series (1)

Solution détaillée de toutes les formules de fonction de transfert (fonction d'activation) du réseau neuronal MATLAB

Graphics_ Learnopongl learning notes

基于SSM的校园失物招领平台,源码,数据库脚本,项目导入运行视频教程,论文撰写教程

Kwai 20200412 recruitment
![[concurrent programming] working mechanism and type of thread pool](/img/51/d21428a7c95c0a5177e8198742e78c.jpg)
[concurrent programming] working mechanism and type of thread pool

Markdown learning

ArrayList

Installation of PHP FPM software +openresty cache construction

Osgearth target selection
随机推荐
Pit & ADB wireless debugging of vivo real machine debugging
Markdown directory generation
Animation_ IK overview
Encoding and decoding of golang URL
Jupyter remote server configuration and server startup
Cesium service deployment, and import and display local 3dfiles data
Transmit pictures with Base64 encoding
【Rust 笔记】07-结构体
LinkedList set
Redis cluster series 4
Map的实现类的顺序性
Thymeleaf 404 reports an error: there was unexpected error (type=not found, status=404)
[MySQL] MySQL Performance Optimization Practice: introduction of database lock and index search principle
swagger文档配置
796 · unlock
Graphics_ Games101/202 learning notes
【Rust 笔记】10-操作符重载
Downward compatibility and upward compatibility
Development material set
Golang time format sorting