As shown in the code below, I'd like to make a generic function for some trait Foo
, which can recieve both &String or &str (and also &PathBuf or &Path).
use std::path::Path;
trait Foo { }
impl Foo for str { }
impl Foo for Path { }
fn foo<F: Foo + ?Sized>(_f: &F) {
println!("foo!");
}
fn main() {
let s = String::from("Hello, World");
foo(&s); // - This line doesn't compile
foo("Hello, World?");
}
One way would be to add the following impls too:
impl Foo for String { };
impl Foo for PathBuf { };
However what would be even better is if I can somehow make it work so that anything which implements AsRef<str>
or AsRef<Path>
can be accepted.
What is considered the idiomatic approach here?
Thanks
David