我正在开发我的第一个 Rust 箱(crate),想要通过让API接受 foo(vec!["bar", "baz"])
和 foo(vec![String::from("foo"), String::from("baz")])
两种形式的参数来使其更加用户友好。
到目前为止,我已经成功地让 API 接受了 String
和 &str
类型的参数,但对于 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);
}
}
我得到的编译器错误是:
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`
AsRef<str>
可能比Into<String>
更有用。此外,请注意,通过转换为 String,您可能会不必要地将字符串分配到堆中。 - SOFe