Konubinix' opinionated web of thoughts

Why Precising the Generic in the Impl in Rust

Fleeting

we have to declare T just after impl so we can use it to specify that we’re implementing methods on the type Point<T>. By declaring T as a generic type after impl, Rust can identify that the type in the angle brackets in Point is a generic type rather than a concrete type. We could, for example, implement methods only on Point<f32> instances rather than on Point<T> instances with any generic type. In Listing 10-10 we use the concrete type f32, meaning we don’t declare any types after impl. Filename: src/main.rs struct Point<T> { x: T, y: T, }

impl<T> Point<T> { fn x(&self) -> &T { &self.x } }

impl Point<f32> { fn distance_from_origin(&self) -> f32 { (self.x.powi(2) + self.y.powi(2)).sqrt() } }

https://doc.rust-lang.org/book/ch10-01-syntax.html