Add a matrix multiplication operator like Python?


Unlike other languages like Scala, R and Haskell, for Rust it was decided not to go with arbitrary operator definitions, but instead syntax sugar for certain trait methods (also like Scala).

This accepted Python EP will be implemented in Python 3.5. The reasons mentioned there are relatively language-agnostic. Please go there to read them all, but the gist is:

  • Many number crunching applications (i.e. pretty much most algorithms in existence) profit from matrix and n-dimensional array operations
  • A basic one is, besides elementwise multiplication, the matrix multiplication
  • Alternatives have to rely on converting matrices to specific types that interpret * as matrix multiplication (e.g. e(m(mat1) * mat2) * mat3 for the formula (mat1 Ă— mat2) · mat3), or method calls (mat1 * mat2).dot(mat3) doesn’t look bad, but try dotting a few more times…). Both suck and get unwieldy fast for more complex formulas
1 Like


This can be added after 1.0 since it is 100% backwards compatible. There are many more urgent issues now.



That’s irrelevant, isn’t it? This is a discussion forum. Everyone can choos for themselves where or where not to talk.



@theme @flying_sheep Please, keep comments, conversations and interactions on topic and kind in this forum or any other conversation channels for this project. Rust’s community always welcomes ideas at any time and it encourages constructive conversations and interactions.

That said, I don’t have much to comment on this topic right now. Maybe @bjz has some opinions.



A similar thing was tried for the exponential operator but was closed because it is not common enough operation. From their included table, the exponential operation is much more common than matrix multiplication so they will currently, probably not go for it.

Though, anyone who works with numerics would prefer dedicated operators.



You could use macro_rules to be able to use whichever operator you wanted, and translate it into method calls.

macro_rules! matrix_math {
    ($left:expr @ $right:expr) => {

With usage such as:

matrix_math! {
    m1 @ m2

You could probably make a few patterns that matrix_math! could match against, to allow for multiple expressions inside a single macro invocation.



Yeah, the table is for Python, a non-systems language, but i still find it interesting how much pow is used. More often than /! More often than !=, < and >! And of course more often than all bit operators.

It’s also very useful for custom roots, as sqrt is equivalent to **0.5 and so on for any root.

Pow not being in is a quite sad affair for people working with numerics, of course even more so than the matrix multipliation operator.



Or go full-fledged syntax extension in there to allow for normal code including the matrix multiplication. Smart idea!

1 Like

closed #9

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.