basic-practice/iterators #1156
Replies: 21 comments 12 replies
-
文档真好 么么哒 |
Beta Was this translation helpful? Give feedback.
-
我刷 leetcode 题也是能用迭代器就用迭代器,rusty 的代码真的很优雅 ~ ❤ |
Beta Was this translation helpful? Give feedback.
-
真舒服啊 最后这一段 我之前写kotlin的 对集合操作 array.map().filter() |
Beta Was this translation helpful? Give feedback.
-
看到search 函数 写go 的流下了眼泪 |
Beta Was this translation helpful? Give feedback.
-
‘’‘rust |
Beta Was this translation helpful? Give feedback.
-
请问下下面的代码有 pub fn search_case_insensitive<'a>(query: & str, contents: &'a str) -> Vec<&'a str> {
let query = query.to_lowercase();
contents
.to_lowercase()
.lines()
.filter(|line| line.contains(&query))
.collect()
} |
Beta Was this translation helpful? Give feedback.
-
优雅也是优雅,真出问题的时候找bug也头疼吧 |
Beta Was this translation helpful? Give feedback.
-
are you ready |
Beta Was this translation helpful? Give feedback.
-
rust 是世界上最好的语言. |
Beta Was this translation helpful? Give feedback.
-
let query = args.next().ok_or("Didn't get a query string")?;
let file_path = args.next().ok_or("Didn't get a file path")?; 真好看呐 |
Beta Was this translation helpful? Give feedback.
-
impl Config {
pub fn build(mut args: impl Iterator<Item = String>,) -> Result<Config, &'static str> {
args.next();
let (query, file_path, ignore_case) = Config::parse_arguements(args).unwrap_or_else(|err| {
eprintln!("Problem parsing arguments: {err}");
process::exit(1);
});
Ok(Config {query,file_path,ignore_case,})
}
fn parse_arguements(mut args: impl Iterator<Item = String>) -> Result<(String, String, bool), &'static str> {
let mut query = String::new();
let mut file_path = String::new();
let mut ignore_case = env::var("IGNORE_CASE").map_or(false, |var| var.eq("1"));
while let Some(arg) = args.next() {
match arg.as_str() {
"-q" | "--query" => {
query = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a query string"),
}
},
"-p" | "--path" => {
file_path = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a file path"),
};
},
"-i" | "--ignore_case" => {
ignore_case = match args.next() {
Some(arg) if arg.as_str().eq("true") => true,
Some(arg) if arg.as_str().eq("false") => false,
_ => return Err("wrong input after -i or --ignore_case")
};
}
_ => return Err("Illegal arguments")
};
};
Ok((query, file_path, ignore_case))
}
} 这一章节结束以后最终的成果 |
Beta Was this translation helpful? Give feedback.
-
太抽象反而不太好。 |
Beta Was this translation helpful? Give feedback.
-
impl Config {
} |
Beta Was this translation helpful? Give feedback.
-
新手求教个问题,类似此项目如何直接使用(比如从github上clone下来之后),不能每次要cd到minigrep里再cargo run吧 |
Beta Was this translation helpful? Give feedback.
-
// main.rs
use std::env;
use std::process;
use minigrep::Config;
use minigrep::run;
fn main() {
let config = Config::from(env::args()).unwrap_or_else(|err| {
eprintln!("Problem parsing arguments: {err}");
process::exit(1);
});
println!("Searching for {:?} in [{}]:", config.query, config.filename);
if let Err(e) = run(config) {
eprintln!("Application error: {e}");
process::exit(1);
}
} // lib.rs
use std::env;
use std::fs;
use std::error::Error;
pub struct Config {
pub query: String,
pub filename: String,
pub ignore_case: bool,
}
impl Config {
pub fn from(mut args: impl Iterator<Item = String>) -> Result<Config, &'static str> {
args.next();
let query = match args.next() {
Some(args) => args,
None => return Err("Didn't get a query string"),
};
let filename = match args.next() {
Some(args) => args,
None => return Err("Didn't get a file name"),
};
let ignore_case = env::var("IGNORE_CASE").map_or_else(
|_| args.next().map_or(
false,
|flag| flag.to_lowercase() == "--ignore-case" || flag.to_lowercase() == "-i"
),
|val| val == "1",
);
Ok(Config { query, filename, ignore_case })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(&config.filename)?;
let result = if config.ignore_case {
search_numbered_ignore_case(&config.query, &contents)
} else {
search_numbered(&config.query, &contents)
};
if result.len() > 0 {
for (index, line) in result {
println!("\tline {:4}: {line}", index + 1);
}
} else {
println!("\tNot found");
}
Ok(())
}
fn search_numbered<'a>(query: &str, contents: &'a str) -> Vec<(usize, &'a str)> {
contents.lines().enumerate().filter(|(_, line)| line.contains(query)).collect()
}
// case insensitive and with line number
fn search_numbered_ignore_case<'a>(query: &str, contents: &'a str) -> Vec<(usize, &'a str)> {
let query = &query.to_lowercase();
contents.lines().enumerate().filter(|(_, line)| line.to_lowercase().contains(query)).collect()
} |
Beta Was this translation helpful? Give feedback.
-
pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { |
Beta Was this translation helpful? Give feedback.
-
完结撒花✿✿ヽ(°▽°)ノ✿ |
Beta Was this translation helpful? Give feedback.
-
basic-practice/iterators
https://course.rs/basic-practice/iterators.html
Beta Was this translation helpful? Give feedback.
All reactions