Chapter 12. Operator Overloading
In the Mandelbrot set plotter we showed in Chapter 2, we used the num
crateâs Complex
type to represent a number on the complex plane:
#[derive(Clone, Copy, Debug)]
struct
Complex
<
T
>
{
/// Real portion of the complex number
re
:T
,
/// Imaginary portion of the complex number
im
:T
,
}
We were able to add and multiply Complex
numbers just like any built-in numeric type, using Rustâs +
and *
operators:
z
=
z
*
z
+
c
;
You can make your own types support arithmetic and other operators, too, just by implementing a few built-in traits. This is called operator overloading, and the effect is much like operator overloading in C++, C#, Python, and Ruby.
The traits for operator overloading fall into a few categories depending on what part of the language they support, as shown in Table 12-1. In this chapter, weâll cover each category. Our goal is not just to help you integrate your own types nicely into the language, but also to give you a better sense of how to write generic functions like the dot product function described in âReverse-Engineering Boundsâ that operate on types most naturally used via these operators. The chapter should also give some insight into how some features of the language itself are implemented.
Category | Trait | Operator |
---|---|---|
Unary operators | std::ops::Neg |
-x |
std::ops::Not |
!x |
|
Arithmetic operators | std::ops::Add |
x + y |
std::ops::Sub |
x - y |
|
std::ops::Mul |
x * ... |
Get Programming Rust, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.