|
|
Log in / Subscribe / Register

Rust operator overloading

Rust operator overloading

Posted Feb 28, 2022 2:41 UTC (Mon) by tialaramex (subscriber, #21167)
In reply to: Moving the kernel to modern C by camhusmj38
Parent article: Moving the kernel to modern C

In fact Rust isn't really overloading at all, what's happening in Rust is that types get to implement some langitem Traits whose functions are invoked by operators. Without those trait implementations, you can't use these "overloadable" operators on a user-defined type at all. For example if my type Apple doesn't implement PartialEq you just can't write thisApple == thatApple, it won't compile. There was no "overloading" in the strict sense.

And where C++ is very profligate with these overloads, Rust is conservative, for example recently there was work to let you do more natural things with Wrapping types, so e.g. today you write

let a = Wrapping<i8>(127);
let b = Wrapping<i8>(1);
let c = a + b;
/* now c is Wrapping<i8>(-128) */

The authors originally thought it would be nice if this worked:

let a = Wrapping<i8>(127);
let b: i8 = 1;
let c = a + b;
/* authors thought it's reasonable c is Wrapping<i8>(-128) but is that definitely what was expected?*/

After feedback to their patches they agreed this could be surprising and instead only implemented *Assign Traits, thus:

let mut a = Wrapping<i8>(127);
let b: i8 = 1;
a += b;
/* The type of a hasn't changed, so it is now Wrapping<i8>(-128) and that makes sense */

In Rust for Linux they deliberately didn't implement most of these "operator" traits for String and similar types which need implied allocation, because Linus doesn't like implied allocation.

Two asides, whilst C++ can't do anything about it now, I'm convinced that subtyping is a bad idea and Rust's choice to provide inheritance only for Traits (ie you can inherit behaviour but not state) was the Right Thing there too. Multiple inheritance the way C++ is unambiguously a bad idea.

And, std::array is an example of C++ refusing to just fix the language. The built-in array in C 89 sucks. C++ inherits that, so the built-in array in C++ 98 sucks. And instead in modern C++ std::array is offered as a substitute, the built-in array syntax is just roped off as dangerous trash not to be used. Rust took the right stance here, in Rust 1.0 the arrays are not good, they're better than in C 89 (and thus modern C++) but they're far worse than Rust's library container types, unrelated examples in documentation ended up using a Vec because it works. Unlike C++ the built-in array wasn't left to die, and as of Rust 2021 the array type is pretty nice, it can do all the things you'd expect a container type to do, and only has a few small warts left to fix.


to post comments


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds