I'm working on my first Rust crate and I wanted to make my API a bit more user friendly by allowing both foo(vec!["bar", "baz"])
and foo(vec![String::from("foo"), String::from("baz")])
.
So far I've managed to accept both String
and &str
but I'm struggling to do the same for Vec<T>
.
fn foo<S: Into<String>>(string: S) -> String {
string.into()
}
fn foo_many<S: Into<String>>(strings: Vec<S>) -> Vec<String> {
strings.iter().map(|s| s.into()).collect()
}
fn main() {
println!("{}", foo(String::from("bar")));
println!("{}", foo("baz"));
for string in foo_many(vec!["foo", "bar"]) {
println!("{}", string);
}
}
The compiler error I get is:
error[E0277]: the trait bound `std::string::String: std::convert::From<&S>` is not satisfied
--> src/main.rs:6:30
|
6 | strings.iter().map(|s| s.into()).collect()
| ^^^^ the trait `std::convert::From<&S>` is not implemented for `std::string::String`
|
= help: consider adding a `where std::string::String: std::convert::From<&S>` bound
= note: required because of the requirements on the impl of `std::convert::Into<std::string::String>` for `&S`