【发布时间】:2019-07-26 16:01:03
【问题描述】:
我正在开发我的第一个 Rust crate,我希望通过同时允许 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 generics vector rust