小编Eli*_*ing的帖子

返回依赖于函数内分配的数据的延迟迭代器

我是Rust的新手并阅读了Rust编程语言,在错误处理部分有一个"案例研究",描述了一个程序,使用csvrustc-serialize库(getopts用于参数解析)从CSV文件中读取数据.

作者编写了一个函数search,该函数使用一个csv::Reader对象逐步执行csv文件的行,并将那些"city"字段与指定值匹配的条目收集到一个向量中并返回它.我采取了与作者略有不同的方法,但这不应该影响我的问题.我的(工作)函数看起来像这样:

extern crate csv;
extern crate rustc_serialize;

use std::path::Path;
use std::fs::File;

fn search<P>(data_path: P, city: &str) -> Vec<DataRow>
    where P: AsRef<Path>
{
    let file = File::open(data_path).expect("Opening file failed!");
    let mut reader = csv::Reader::from_reader(file).has_headers(true);

    reader.decode()
          .map(|row| row.expect("Failed decoding row"))
          .filter(|row: &DataRow| row.city == city)
          .collect()
}
Run Code Online (Sandbox Code Playgroud)

DataRow类型仅仅是一个记录,

#[derive(Debug, RustcDecodable)]
struct DataRow {
    country: String,
    city: String,
    accent_city: String,
    region: String,
    population: Option<u64>, …
Run Code Online (Sandbox Code Playgroud)

iterator allocation heap-memory lifetime rust

7
推荐指数
1
解决办法
342
查看次数

标签 统计

allocation ×1

heap-memory ×1

iterator ×1

lifetime ×1

rust ×1