r/rust • u/Imaginary-Room2286 • 7d ago
Is it just me or does the syntax seem wayy too complicated for even someone coming from C++?
I recently decided to learn rust and i was implementing just a basic math vector in it...
use std::fmt;
use std::ops::Add;
struct Vector<T> {
x: T,
y: T,
z: T,
}
impl<T> Vector<T> {
fn new(x: T, y: T, z: T) -> Self {
Self { x, y, z }
}
}
// Operator overloading for +
impl<T: Add<Output = T>> Add for Vector<T> {
type Output = Vector<T>;
fn add(self, other: Self) -> Self::Output {
Vector {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
}
}
}
// Display implementation
impl<T: fmt::Display> fmt::Display for Vector<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}i + {}j + {}k", self.x, self.y, self.z)
}
}
fn main() {
let v1 = Vector::new(1, 2, 3);
let v2 = Vector::new(4, 5, 6);
let v3 = v1 + v2;
println!("{v3}");
}
```
it just seems really complicated for no reason...
like why do we need Output = T or Self::Output or even writing <T> twice every time we are impl it? It just seems very weirdly verbose to me and a bit unnecessary... Is there a better way to do this? For all the tutorials I have seen this is how people are doing Generics in rust....
Edit: Full disclosure i tried doing this myself thrice and everytime I didnt do things like mut fmt::Formatter<'_> or fmt::Result and it was just all very confusing... ultimately I gpt-ed it just to see what the way was and i still found it to be very counter-intuitive
