I am confused about the generic parameter for the impl keyword in Rust.
To explain what I am confused about, I am currently going through the rustling exercises. I am doing the generics part. The second question which can be seen here is to make the Wrapper struct generic.
Easy, the solution is:
struct Wrapper<T> {
value: T,
}
impl<T> Wrapper<T> {
pub fn new(value: T) -> Self {
Wrapper { value }
}
}
But I ask myself, why does impl have to also have a type parameter? Why impl<T> Wrapper<T> and not just impl Wrapper<T>?
I could not answer that question but on moving on to the next exercise, which can be seen here there is another generic question, which I solved by having this:
use std::fmt::Display;
pub struct ReportCard<T:Display> {
pub grade: T,
pub student_name: String,
pub student_age: u8,
}
impl<T:Display> ReportCard<T> {
pub fn print(&self) -> String {
format!("{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade.to_string())
}
}
Now I am wondering, why is this right, and the following wrong:
pub struct ReportCard<T:Display> {
pub grade: T,
pub student_name: String,
pub student_age: u8,
}
impl<T:Display> ReportCard<T:Display> {
pub fn print(&self) -> String {
format!("{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade.to_string())
}
}
I think the crux of my problem is, I do not really understand the generics syntax. And where to put the generic type parameter, especially when there is an impl block.
Does anyone have an explanation on how these syntax is supposed to be used?