lotsoftools

Understanding Rust Error E0368

Rust Error E0368 Explained

Rust error E0368 occurs when a binary assignment operator, such as += or ^=, is applied to a type that does not support it. This error can be resolved by ensuring the appropriate trait is implemented for the type in question.

Erroneous Code Example

#![allow(unused)]
fn main() {
  let mut x = 12f32; // error: binary operation `<<` cannot be applied to type `f32`

  x <<= 2;
}

In the above example, we tried to apply the << binary assignment operator to a floating-point variable x of type f32. However, this operator is not supported for the f32 type, resulting in error E0368.

Fixing the Error

To resolve error E0368, you can change the variable type to one that supports the desired binary operation. In our previous example, changing the variable type to u32 (unsigned 32-bit integer) will fix the error:

#![allow(unused)]
fn main() {
  let mut x = 12u32; // the `u32` type does implement the `ShlAssign` trait

  x <<= 2; // ok!
}

Operator Overloading

It is possible to implement the [OP]Assign traits from std::ops to overload most operators for your custom types. However, implementing the Add trait alone will not automatically implement the AddAssign trait. You will need to implement the AddAssign trait separately, as demonstrated in the following example:

use std::ops::{Add, AddAssign};

struct Foo(u32);

impl Add for Foo {
  type Output = Foo;

  fn add(self, rhs: Foo) -> Foo {
      Foo(self.0 + rhs.0)
  }
}

impl AddAssign for Foo {
  fn add_assign(&mut self, rhs: Foo) {
      self.0 += rhs.0;
  }
}

fn main() {
  let mut x: Foo = Foo(5);
  x += Foo(7); // ok!
}

In the above example, the AddAssign trait was implemented for the custom type Foo, allowing the += operator to be used without error.