当前位置:网站首页>[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
边栏推荐
- UE4 source code reading_ Bone model and animation system_ Animation compression
- Introduction to hexadecimal coding
- Explain sizeof, strlen, pointer, array and other combination questions in detail
- Use of ue5 QRcode plug-in
- Detailed explanation of all transfer function (activation function) formulas of MATLAB neural network
- Unity editor expansion - the design idea of imgui
- [cloud native] introduction and use of feign of microservices
- [concurrent programming] Table hopping and blocking queue
- Map的实现类的顺序性
- [RPC] RPC remote procedure call
猜你喜欢
![[RPC] RPC remote procedure call](/img/dc/872204ea47fcff04cdb72e18a2a4ef.jpg)
[RPC] RPC remote procedure call

Simply start with the essence and principle of SOM neural network

单调栈-42. 接雨水

Abstract classes and interfaces

十六进制编码简介

Introduction to Base64 coding

matlab神经网络所有传递函数(激活函数)公式详解

ArrayList
![[concurrent programming] concurrent tool class of thread](/img/16/2b4d2b3528b138304a1a3918773ecf.jpg)
[concurrent programming] concurrent tool class of thread

UE4 source code reading_ Bone model and animation system_ Animation compression
随机推荐
Downward compatibility and upward compatibility
[concurrent programming] thread foundation and sharing between threads
Campus lost and found platform based on SSM, source code, database script, project import and operation video tutorial, Thesis Writing Tutorial
matlab神经网络所有传递函数(激活函数)公式详解
Introduction to hexadecimal coding
如何应对数仓资源不足导致的核心任务延迟
Ue5 opencv plug-in use
使用base64编码传图片
【Rust 笔记】08-枚举与模式
Golang time format sorting
二进制转十进制,十进制转二进制
Mall management system of database application technology course design
Unity4.3.1 engine source code compilation process
Development material set
单调栈-42. 接雨水
Chocolate installation
Introduction to Base64 coding
Golang 字符串分割,替换和截取
Installation of PHP FPM software +openresty cache construction
【更新中】微信小程序学习笔记_3