rust - 如何找到数组、向量或切片中元素的索引?

标签 rust

我需要在字符串向量中找到一个元素的索引。这是我到目前为止得到的:

fn main() {
    let test: Vec<String> = vec![
        "one".to_string(),
        "two".to_string(),
        "three".to_string(),
        "four".to_string(),
    ];

    let index: i32 = test
        .iter()
        .enumerate()
        .find(|&r| r.1.to_string() == "two".to_string())
        .unwrap()
        .0;
}

它产生一个错误:

error[E0308]: mismatched types
  --> src/main.rs:9:22
   |
9  |       let index: i32 = test
   |  ______________________^
10 | |         .iter()
11 | |         .enumerate()
12 | |         .find(|&r| r.1.to_string() == "two".to_string())
13 | |         .unwrap()
14 | |         .0;
   | |__________^ expected i32, found usize

我假设那是因为 enumerate() 返回一个 (usize, _) 的元组(如果我错了请纠正我),但是我如何转换 usizei32 这里?如果有更好的方法,我愿意接受建议。

最佳答案

我认为你应该看看 position方法代替。

fn main() {
    let test = vec!["one", "two", "three"];
    let index = test.iter().position(|&r| r == "two").unwrap();
    println!("{}", index);
}

您可以 test it here .

请注意,这适用于任何迭代器,因此它可用于向量、数组和切片,所有这些都会产生迭代器。

关于rust - 如何找到数组、向量或切片中元素的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30558246/

相关文章:

rust - 如何在 macOS 上修复错误 "couldn' t load codegen backend?

multithreading - 为什么我看不到 thread::spawn 内部打印的任何输出?

tcp - Rust TcpListener 不响应外部请求

arrays - 以最小的开销安全地将所有元素从通用数组 move 到元组中的方法

winapi - 从 2 个 winapi 调用返回不一致的错误

rust - 函数,可变借用

io - 如何从 Rust 中的文件或标准输入执行多态 IO?

rust - 相交着色器从 SSBO 中读取零

rust - 澄清 Rust 生命周期语法

rust - 我可以在闭包中通过引用捕获某些内容,而通过值捕获其他内容吗?