Generics in Trait definition / in Fn definition
⚓ Rust 📅 2025-06-14 👤 surdeus 👁️ 16Hi folks,
Could you please tell me, if there is a difference between the following?
The only difference I can see is that in the second case I won't need to type AsRef<[u8]> again for another (parse_this2) function?
Thank you.
pub trait MyParser {
fn parse_this<T>(self, foobar: T) -> String
where
T: AsRef<[u8]>;
}
impl MyParser for String {
fn parse_this<T>(self, foobar: T) -> String
where
T: AsRef<[u8]>,
{
let s = str::from_utf8(foobar.as_ref()).unwrap_or_default();
format!("{self}{s}",)
}
}
pub trait MyParser2<T>
where
T: AsRef<[u8]>,
{
fn parse_this(self, foobar: T) -> String;
}
impl<T> MyParser2<T> for String
where
T: AsRef<[u8]>,
{
fn parse_this(self, foobar: T) -> String {
let s = str::from_utf8(foobar.as_ref()).unwrap_or_default();
format!("{self}{s}",)
}
}
1 post - 1 participant
🏷️ rust_feed