vector - 如何为向量的迭代器元素添加 Into 的类型注释?

标签 vector rust annotations traits

我有一个向量,其值是由特征定义的,我想在该向量上使用 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`

在这种情况下我应该在哪里放置类型注释以及预期的类型注释是什么?

playground

最佳答案

一种可能是通知 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/

相关文章:

STL - double vector 数组中前导零的问题

java - vector 内的 vector

C++,使用其指针修改 vector 元素

c++ - 如何手动分配 vector 的大小?

hash - 如何从可哈希的库中创建一个不可哈希的、类 C 的枚举?

docker - 版本 `GLIBC_2.29' 未找到

c++ - 使用 gcc 插件获取类注释

multithreading - 如何在 Rust 中访问外部线程局部全局变量?

Javascript、文本注释和想法

java - JPA + Hibernate + Spring - 父子持久化生成 ID 导致外键错误