Skip to content

Instantly share code, notes, and snippets.

@sam0x17
Created May 23, 2023 13:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sam0x17/23ca1495bc0edf0159d2bdc1d7839846 to your computer and use it in GitHub Desktop.
Save sam0x17/23ca1495bc0edf0159d2bdc1d7839846 to your computer and use it in GitHub Desktop.
Rust trait generic over all types of string references
pub trait GenericStr {
fn as_str_generic(&self) -> &str;
}
impl GenericStr for &String {
fn as_str_generic(&self) -> &str {
self.as_str()
}
}
impl GenericStr for String {
fn as_str_generic(&self) -> &str {
self.as_str()
}
}
impl GenericStr for &str {
fn as_str_generic(&self) -> &str {
*self
}
}
fn foo<S: GenericStr>(input: S) -> String {
format!("you gave me: {}", input.as_str_generic())
}
fn main() {
println!("{}", foo(String::from("a String")));
println!("{}", foo(&String::from("a &String")));
println!("{}", foo(String::from("a &str").as_str()));
println!("{}", foo("a &'static str"));
}
@sam0x17
Copy link
Author

sam0x17 commented May 23, 2023

Don't use this, use AsRef<str>:

fn foo<S: AsRef<str>>(input: S) -> String {
    format!("you gave me: {}", input.as_ref())
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment