Understanding and Fixing Rust Error E0369
Rust Error E0369: Unsupported Binary Operation
Rust error E0369 occurs when a binary operation is attempted on a type that doesn't support it, for example, using the '<<' (left shift) operation on a floating-point number.
Erroneous code example:
#![allow(unused)]
fn main() {
let x = 12f32;
x << 2;
}
Fixed code example:
#![allow(unused)]
fn main() {
let x = 12u32;
x << 2;
}
How to fix Rust Error E0369
To fix Rust error E0369, you should check if the type in question implements the binary operation. If not, you can either change the type or implement the operation using a trait from the std::ops module.
Implementing std::ops traits for custom types
You can implement most operators for your custom types by implementing traits from the std::ops module. Here's an example of implementing Add for a custom Point struct:
use std::ops::Add;
struct Point {
x: i32,
y: i32,
}
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
fn main() {
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 3, y: 4 };
let p3 = p1 + p2;
println!("p3: {{x: {}, y: {}}}", p3.x, p3.y);
}
Handling string concatenation
When concatenating strings, Rust requires ownership of the string on the left side. If you need to add something to a string literal, move the literal to the heap by allocating it with to_owned(), like this:
let concatenated_string = "Your text".to_owned() + " more text";