我有一个向量,其值是由特征定义的,我想在该向量上使用 Iterator
特征提供的方法。
这是我的用例的简化代码:
案例A
fn beta<T: Into<i32>>(s: Vec<T>) {
for x in s {
println!("{:?}", x.into());
}
}
情况B
fn beta2<U: Into<i32>>(s: Vec<U>) {
for x in s.iter() {
println!("{:?}", x.into());
}
}
案例 A 有效并按预期编译和运行。 情况 B 但是会引发编译时错误:
error[E0282]: type annotations needed
--> src/main.rs:11:26
|
11 | println!("{:?}", x.into());
| ^^^^^^^^ cannot infer type for `T`
在这种情况下我应该在哪里放置类型注释以及预期的类型注释是什么?
最佳答案
一种可能是通知 beta2
那&U
(与 U
相反)实现 Into<i32>
:
fn beta2<U>(s: Vec<U>)
where
for<'a> &'a U: Into<i32>,
{
for x in s.iter() {
println!("{:?}", x.into());
}
}
请注意Into
接受 self
而不是&self
,即它消耗了它的参数。因此,您必须找到某种方法来转换借来的 x
转化为拥有的值(value):
fn beta2<U, U2>(s: Vec<U>)
where
U: std::borrow::ToOwned<Owned = U2>,
U2: Into<i32> + std::borrow::Borrow<U>,
{
for x in s.iter() {
println!("{:?}", x.to_owned().into());
}
}
关于vector - 如何为向量的迭代器元素添加 Into 的类型注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52933363/