basic-practice/iterators #1156
Replies: 22 comments 14 replies
-
文档真好 么么哒 |
Beta Was this translation helpful? Give feedback.
-
感谢大佬 |
Beta Was this translation helpful? Give feedback.
-
我刷 leetcode 题也是能用迭代器就用迭代器,rusty 的代码真的很优雅 ~ ❤ |
Beta Was this translation helpful? Give feedback.
-
基础完结撒花 |
Beta Was this translation helpful? Give feedback.
-
好帅的闭包 |
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.
-
感谢大佬 |
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.
-
main.rs use std::{process, env};
use mini_grep::grep;
fn main() {
let config = grep::Config::new(env::args()).unwrap_or_else(|err| {
eprintln!("ERROR: {}", err);
process::exit(1);
});
let content = grep::run(&config).unwrap_or_else(|err| {
eprintln!("ERROR: {}", err);
process::exit(1);
});
let result = grep::search(&config.keyword, &content, config.ignore_case);
for item in result {
println!("{}", item);
}
} lib.rs #[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let keyword = "hello";
let content = "\
hi rust:
I can print \"hello world!\"
Great!!";
assert_eq!(vec!["I can print \"hello world!\""], grep::search(keyword, content, false));
}
}
pub mod grep {
use std::env;
use std::env::Args;
use std::fs::File;
use std::io::{Error, Read};
#[derive(Debug)]
pub struct Config {
pub path: String,
pub keyword: String,
pub ignore_case: bool,
}
impl Config {
pub fn new(mut args: Args) -> Result<Self, &'static str> {
args.next();
let keyword = args.next().ok_or("Please provide a keyword")?;
let path = args.next().ok_or("Please provide a path")?;
Ok(Config {
path,
keyword,
ignore_case: env::var("IGNORE_CASE").is_ok(),
})
}
}
pub fn run(config: &Config) -> Result<String, Error> {
let mut content = String::new();
File::open(&config.path)?.read_to_string(&mut content)?;
Ok(content)
}
pub fn search<'a>(keyword: &'a str, content: &'a str, ignore_case: bool) -> Vec<&'a str> {
let word = if ignore_case {
keyword.to_lowercase()
} else { keyword.to_string() };
content.lines().filter(|line| {
let line_lowercase = if ignore_case {
line.to_lowercase()
} else { line.to_string() };
line_lowercase.contains(&word)
}).collect()
}
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
basic-practice/iterators
https://course.rs/basic-practice/iterators.html
Beta Was this translation helpful? Give feedback.
All reactions