当前位置:网站首页>[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
边栏推荐
- matlab神經網絡所有傳遞函數(激活函數)公式詳解
- Golang 中string和int类型相互转换
- Development experience and experience
- UE4 source code reading_ Bone model and animation system_ Animation compression
- 数据分析练习题
- [updating] wechat applet learning notes_ three
- Cloudcompare learning (1) - cloudcompare compilation and common plug-in implementation
- 數據庫應用技術課程設計之商城管理系統
- 【更新中】微信小程序学习笔记_3
- 【音视频】ijkplayer错误码
猜你喜欢

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

UE4 source code reading_ Bone model and animation system_ Animation node

Unity Editor Extension - drag and drop

Easy touch plug-in

C#课程设计之员工信息管理系统

Minimap plug-in

Unity learning notes

Explain sizeof, strlen, pointer, array and other combination questions in detail

图像处理8-CNN图像分类

Collection interface
随机推荐
Swagger document configuration
Golang's range
[updating] wechat applet learning notes_ three
Unity learning notes
796 · 开锁
Osganimation library parsing
[RPC] RPC remote procedure call
Why can void * be a general pointer
UE4 source code reading_ Bone model and animation system_ Animation process
Redis data structure
Markdown learning
producer consumer problem
十六进制编码简介
Talking about: is the HashSet set ordered or disordered /hashset set unique, why can we store elements with the same content
Development material set
Constraintlayout's constraintset dynamically modifies constraints
【Rust笔记】05-错误处理
Huawei interview summary during the epidemic
Abstract classes and interfaces
Unity editor expansion - the framework and context of unity imgui