| > Who determines the output type of "a + b"? "a"? "b"? Both? Are there implicit type conversions? The Add trait is defined in `std::ops::Add` as: pub trait Add<RHS = Self> {
type Output;
fn add(self, rhs: RHS) -> Self::Output;
}
(You can find the documentation on <https://doc.rust-lang.org/1.26.2/std/ops/trait.Add.html>)Both the type of the `self` parameter and the concrete type of `RHS` determines which trait impl matches. For example: `2 + 2` chooses the `impl Add<i32> for i32 { type Output = i32; ... }` implementation (literal integers are of type `i32`). Something like `2 + &2` would choose `impl<'a> Add<&'a i32> for i32`. > There's nothing here about what Rust does about conversions, but that may be covered in one of the other many parts of this series. With operators, there are no implicit conversions involved, AFAIK. So all Rust can do is try and infer the type you want. For literal numbers, it can do so in a limited fashion. As seen above, if you write `let x = 42;` the type is inferred as `i32`. If you write `foo(666)` with `fn foo(x: u64)`, the literal 666 is inferred to be meant as `666u64`. > The good news is that the Rust programming book is finally coming out in just 6 more days. So there's something better to read than this. You can already read it here: https://doc.rust-lang.org/book/second-edition/index.html :) |
(I’m still simplifying this a little, because specialisation is a thing which does allow overlapping implementations, but it must be opted into by the broad implementation by writing `default fn` instead of `fn`.)