如何在 Rust 中执行类似于此 D 和 Java 代码的操作?
Java:
import java.nio.file.*;
import java.io.*;
public class Main {
public static void main( String[] args ) throws IOException
{
Files.lines(Paths.get("/home/kozak/test.txt"))
.filter(s -> s.endsWith("/bin/bash"))
.map(s -> s.split(":", 2)[0])
.forEach(System.out::println);
}
}
D语言:
import std.algorithm;
import std.stdio;
void main() {
File("/home/kozak/test.txt")
.byLine
.filter!((s)=>s.endsWith("/bin/bash"))
.map!((s)=>s.splitter(":").front)
.each!writeln;
}
我试过了,但我迷失了所有这些所有权的东西
我的使用rust 代码:
use std::io::BufReader;
use std::fs::File;
use std::io::BufRead;
use std::io::Lines;
fn main() {
let file = match File::open("/etc/passwd") {
Ok(file) => file,
Err(..) => panic!("room"),
};
let mut reader = BufReader::new(&file);
for line in reader.lines().filter_map(
|x| if match x { Ok(v) => v.rmatches("/bin/bash").count() > 0, Err(e) => false}
{ match x { Ok(v2) => Some(v2.split(":").next()), Err(e2) => None }} else
{ None })
{
print!("{}", line.unwrap() );
}
}
最佳答案
给你:
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let f = BufReader::new(File::open("/etc/passwd").unwrap());
let it = f.lines()
.map(|line| line.unwrap())
.filter(|line| line.ends_with("/bin/bash"))
.map(|line| line.split(":").next().unwrap().to_owned());
for p in it {
println!("{}", p);
}
}
这段代码虽然为每个第一个拆分部分分配了一个单独的字符串,但我认为如果没有流式迭代器就不可能避免它。当然,这里的错误处理非常宽松。
我想命令式方法会更惯用,尤其是在错误处理方面:
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let f = BufReader::new(File::open("/etc/passwd").unwrap());
for line in f.lines() {
match line {
Ok(line) => if line.ends_with("/bin/bash") {
if let Some(name) = line.split(":").next() {
println!("{}", name);
} else {
println!("Line does not contain ':'");
}
},
Err(e) => panic!("Error reading file: {}", e)
}
}
}
关于filter - 如何读取、过滤和修改文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30327997/