O'Reilly logo

Programming Rust by Jason Orendorff, Jim Blandy

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 12. Operator Overloading

There is a range of views among mathematicians and philosophers as to the exact scope and definition of mathematics. ...All have severe problems, none has widespread acceptance, and no reconciliation seems possible.

Wikipedia, “Mathematics”

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. The remaining sections of this chapter cover each category in turn.

Table 12-1. Summary of traits for operator overloading
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 * y
std::ops::Div x / y
std::ops::Rem x % y
Bitwise operators std::ops::BitAnd x & y

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required