下面是操场链接,也是下面的代码片段:
fn test_inner<Tag: AsRef<str>, Tags: IntoIterator<Item = Tag> + std::fmt::Debug>(tags: Tags) {
println!("{:?}", tags);
}
fn test<Tag: AsRef<str>, Tags: IntoIterator<Item = Tag> + std::fmt::Debug>(tags: Option<Tags>) {
test_inner(tags.unwrap_or(["abc"]));
// test_inner(tags.unwrap_or(["abc"].into_iter()));
}
fn main() {
test(None::<&[&str]>);
}现在我发现了错误:
| test_inner(tags.unwrap_or(["abc"]));
| ^^^^^^^ expected type parameter `Tags`, found array `[&str; 1]`
|
= note: expected type parameter `Tags`
found array `[&str; 1]`如何从tags.unwrap_or()返回属性对象以满足T: <Tag: AsRef<str>, Tags: IntoIterator<Item = Tag>>
我仍然在学习生锈,我的意图是包装内部方法,以便外部调用者可以将None传递给tags参数,如果接近方向完全错误,请帮助纠正它。
发布于 2021-12-25 13:06:31
不确定是否知道该选项,但编写test的一个简单方法是使用显式if
fn test<Tag: AsRef<str>, Tags: IntoIterator<Item = Tag> + std::fmt::Debug>(tags: Option<Tags>) {
if let Some(tags) = tags {
test_inner(tags)
} else {
test_inner(["abc"])
}
}这与unwrap_or()版本的不同之处在于,在对test_inner()的两次不同调用中,使用了两种不同的类型。带有unwrap_or()的版本试图给出一个类型为Tags的值,但这不能工作,因为选择Tags类型的是调用方。像["abc"]这样的特定值与调用方确定的泛型类型没有相同的类型。
https://stackoverflow.com/questions/70478229
复制相似问题