简体   繁体   English

如何正确将此文件行向量传递给 Rust 中的 function?

[英]How do I correctly pass this vector of file lines to my function in Rust?

I'm trying to read a file into a vector, then print out a random line from that vector.我正在尝试将文件读入向量,然后从该向量中打印出随机行。

What am I doing wrong?我究竟做错了什么?

I'm asking here because I know I'm making a big conceptual mistake, but I'm having trouble identifying exactly where it is.我在这里问是因为我知道我犯了一个很大的概念错误,但我无法准确确定它在哪里。

I know the error -我知道错误 -

error[E0308]: mismatched types 26 |错误[E0308]:类型不匹配 26 | processor(&lines) |处理器(&lines) | ^^^^^^ expected &str , found struct std::string::String ^^^^^^ 预期&str ,找到 struct std::string::String

And I see that there's a mismatch - but I don't know how to give the right type, or refactor the code for that (very short) function.而且我看到有一个不匹配 - 但我不知道如何给出正确的类型,或者重构那个(非常短的)function 的代码。

My code is below:我的代码如下:

use std::{
    fs::File,
    io::{prelude::*, BufReader},
    path::Path,
};

fn lines_from_file(filename: impl AsRef<Path>) -> Vec<String> {
    let file = File::open(filename).expect("no such file");
    let buf = BufReader::new(file);
    buf.lines()
        .map(|l| l.expect("Could not parse line"))
        .collect()
}

fn processor(vectr: &Vec<&str>) -> () {
    let vec = vectr;
    let index = (rand::random::<f32>() * vec.len() as f32).floor() as usize;

    println!("{}", vectr[index]);
}

fn main() {
    let lines = lines_from_file("./example.txt");
    for line in lines {
        println!("{:?}", line);
    }
    processor(&lines);
}

While you're calling the processor function you're trying to pass a Vec<String> which is what the lines_from_file returns but the processor is expecting a &Vec<&str> .当您调用processor function 时,您正在尝试传递Vec<String> ,这是lines_from_file返回的内容,但processor期待&Vec<&str> You can change the processor to match that expectation:您可以更改处理器以匹配该期望:

fn processor(vectr: &Vec<String>) -> () {
    let vec = vectr;
    let index = (rand::random::<f32>() * vec.len() as f32).floor() as usize;

    println!("{}", vectr[index]);
}

The main function: main function:

fn main() {
    let lines = lines_from_file("./example.txt");
    for line in &lines {. //  &lines to avoid moving the variable
        println!("{:?}", line);
    }
    processor(&lines);
}

More generally, a String is not the same as a string slice &str , therefore Vec<String> is not the same as Vec<&str> .更一般地, String与字符串切片&str不同,因此Vec<String>Vec<&str>不同。 I'd recommend checking the rust book: https://doc.rust-lang.org/nightly/book/ch04-03-slices.html?highlight=String#string-slices我建议查看 rust 书: https://doc.rust-lang.org/nightly/book/ch04-03-slices.html?highlight

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM