当前位置:网站首页>[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
边栏推荐
- LinkList
- Image processing 8-cnn image classification
- Redis cluster series 4
- VIM learning notes from introduction to silk skating
- 【Rust 笔记】08-枚举与模式
- Sequence of map implementation classes
- UE4 source code reading_ Bone model and animation system_ Animation node
- Downward compatibility and upward compatibility
- 【Rust 笔记】10-操作符重载
- Exe file running window embedding QT window
猜你喜欢

Unity Editor Extension - drag and drop

Dotween plug-in

Thymeleaf 404 reports an error: there was unexpected error (type=not found, status=404)
![[redis] redis persistent RDB vs AOF (source code)](/img/57/b6a86c49cedee31fc00dc5d1372023.jpg)
[redis] redis persistent RDB vs AOF (source code)

Kunlunbase meetup is waiting for you!

Campus lost and found platform based on SSM, source code, database script, project import and operation video tutorial, Thesis Writing Tutorial

matlab神經網絡所有傳遞函數(激活函數)公式詳解

Base64和Base64URL

Redis data structure

C#课程设计之员工信息管理系统
随机推荐
Cloudcompare learning (1) - cloudcompare compilation and common plug-in implementation
Animation_ IK overview
Vscode, idea, VIM development tool shortcut keys
Solution détaillée de toutes les formules de fonction de transfert (fonction d'activation) du réseau neuronal MATLAB
Introduction to hexadecimal coding
Simply start with the essence and principle of SOM neural network
[RPC] RPC remote procedure call
Initial unity
Development material set
Base64 and base64url
单调栈-42. 接雨水
Unity editor expansion - window, sub window, menu, right-click menu (context menu)
Dotween plug-in
Unity Editor Extension - drag and drop
[concurrent programming] concurrent tool class of thread
[concurrent programming] working mechanism and type of thread pool
单调栈-503. 下一个更大元素 II
GIS实战应用案例100篇(七十八)-多规合一数据库设计及数据入库
Gradle's method of dynamically modifying APK package name
Osgearth target selection