Created
May 23, 2023 13:29
-
-
Save sam0x17/23ca1495bc0edf0159d2bdc1d7839846 to your computer and use it in GitHub Desktop.
Rust trait generic over all types of string references
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't use this, use
AsRef<str>
: