Rust从Option.unwrap_or()返回T:IntoTerator的trait对象



这是操场链接,也是下面的代码片段:

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()返回一个trait对象以满足T: <Tag: AsRef<str>, Tags: IntoIterator<Item = Tag>>

我仍在学习rust,我的意图是包装内部方法,以便外部调用方可以将None传递给tags参数,如果方法方向完全错误,请帮助纠正。

不确定您是否知道该选项,但编写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"]这样的特定值的类型与调用者确定的泛型类型不同。

最新更新