basic-practice/envs #1153
Replies: 35 comments 33 replies
-
is_ok 有一丢丢的不严谨, IGNORE_CASE=0 这样就不行了 |
Beta Was this translation helpful? Give feedback.
-
使用powershell的话可以这样运行 |
Beta Was this translation helpful? Give feedback.
-
尝试完成一下小作业: pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough argments");
}
let query = args[1].clone();
let file_path = args[2].clone();
let ignore_case = match env::var("IGNORE_CASE") {
Err(_) => match args.get(3) {
Some(flag) => flag != "0",
None => false,
},
Ok(_) => true,
};
Ok(Config {
query,
file_path,
ignore_case,
})
} |
Beta Was this translation helpful? Give feedback.
-
最后测试大小写不敏感时候:你如果使用的是PowerShell终端,需要先设置环境变量:$env:IGNORE_CASE=1,然后再用cargo run -- to poem.txt,就可以了 |
Beta Was this translation helpful? Give feedback.
-
感觉这么判断有点废话,老哥们有没有更漂亮的写法? // 从环境变量中获取
let mut case_ignore: bool = env::var("IGNORE_CASE").map_or(false, |val: String| val != "0");
// 从命令行参数中获取
if case_ignore == false {
for arg in args {
if arg == "IGNORE_CASE" {
case_ignore = true;
break;
}
}
} |
Beta Was this translation helpful? Give feedback.
-
// without unit test
// read env first
let case_ignore: bool = std::env::var("IGNORE_CASE").map_or_else(
|_| {
// if env don't exist, try read ignore case in CLI args
args.iter()
.any(|arg| arg.to_lowercase() == "-i" || arg.to_lowercase() == "--ignore-case")
},
|s| s == "0" || s.to_lowercase() == "false", // if env U=IGNORE_CASE exist, check his value
); |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
let ignore_case = match env::var("IGNORE_CASE") {
Ok(v) => v.eq("1"),
_ => match args.next() {
Some(arg) => arg.contains("ignore_case"),
None => false,
},
}; |
Beta Was this translation helpful? Give feedback.
-
impl Config {
pub fn from(args: &Vec<String>) -> Result<Self, &str> {
if args.len() < 3 {
return Err("args not long enough");
}
Ok(Self {
query: args[1].clone(),
file_path: args[2].clone(),
ignore_case: {
let have_ignore_case = std::env::var("IGNORE_CASE").is_ok();
if have_ignore_case {
have_ignore_case
} else {
args[3].eq("1")
}
},
})
}
} |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
这样吗? let ignore_case: bool = env::var("IGNORE_CASE").map_or(
args.iter().any(|arg| arg.to_lowercase().contains("-i")),
|env_value| env_value.eq("1"),
); |
Beta Was this translation helpful? Give feedback.
-
记录下使用环境变量参数IGNORE_CASE="1"或者命令行参数使用 "i" || "--ignore-case",忽略大小写 |
Beta Was this translation helpful? Give feedback.
-
欢迎大家提出意见 impl Config {
// #[warn(dead_code)]
// fn new(args:&[String])->Config{
// let query = &args[1];
// let file_path = &args[2];
// Config { query, file_path }
// }
// 有一点需要额外注意下,从代码惯例的角度出发,new 往往不会失败,毕竟新建一个实例没道理失败
// 所以改成build会比较合适
pub fn build(args:&[String]) -> Result<Config,&'static str> {
let mut query :String = "".to_string();
let mut file_path:String = "".to_string();
// 获取query和file_path
for arg in args{
if &arg[0..2] == "-q" {
query = arg[3..].to_string();
}else if &arg[0..2] == "-f" {
file_path = arg[3..].to_string();
}
}
//错误处理
if query == "" {
return Err("query is empty");
}else if file_path == "" {
return Err("file path is empty");
}
//忽略大小写 any返回的是bool正好符合
let ignore_case = env::var("IGNORE_CASE").map_or_else(
|_| args.iter().any(|arg| {arg.to_lowercase() == "-i" || arg.to_lowercase() == "--ignore-case"}),
|env_value| env_value == "1" || env_value.to_lowercase() == "true");
Ok(Config { query, file_path, ignore_case})
}
} |
Beta Was this translation helpful? Give feedback.
-
结合大家的思路,为的实现方式如下: pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("Not enough arguments.");
}
let query = &args[1];
let file_path = &args[2];
let ignore_case = match env::var("IGNORE_CASE"){
Ok(flag) => match flag.as_str() {
"0" => false,
_ => true,
},
Err(_) =>{
match args.get(3){
Some(arg) => match arg.as_str(){
"ig" | "igc" | "ignore" | "ignorecase" | "ignore_case" => true,
_ => false,
},
None => false,
}
}
};
Ok(Config {
query,
file_path,
ignore_case,
})
} |
Beta Was this translation helpful? Give feedback.
-
环境变量是如何输入的?为何我按照文章里的输入会报错。。。😰 |
Beta Was this translation helpful? Give feedback.
-
咱也来交作业啦: fn aux(string: String) -> bool {
["", "0", "false", "nil", "null", "no", "none"]
.iter()
.all(|falsy| falsy.ne(&string.trim().to_lowercase().as_str()))
}
let ignore_case = match env::var("IGNORE_CASE") {
Ok(string) => aux(string),
Err(_) => args.next().is_some_and(aux),
// 这里是迭代器改进后的写法,不使用迭代器的做法是将上面的 `next()` 改为 `get(3)`
}; |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
有了大家的思路帮助,结合后面的对于clone的移除,完成了课后小习题,实现不用clone以及可以乱序输入参数 //移除clone的使用
} |
Beta Was this translation helpful? Give feedback.
-
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = &args[1];
let file_path = &args[2];
let ignore_case_input = args.get(3);
let ignore_case = env::var("IGNORE_CASE")
.map_or(
match ignore_case_input {
Some(val) if val.eq("ignore_case") => true,
Some(_) | None => false,
}, |var| var.eq("1"));
Ok(
Config {
query: query.to_string(),
file_path: file_path.to_string(),
ignore_case,
}
)
}
} 小作业以及不使用 |
Beta Was this translation helpful? Give feedback.
-
to_lowercase再比较,也有其他选择:eq_ignore_ascii_case |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
我也来实现下,借鉴别人代码,优化地方:自动识别命令符和变量, pub struct Config {
query: String,
file_path: String,
ignore_case: bool,
}
impl Config {
pub fn from(args: &[String]) -> Result<Self, &'static str> {
let command: Vec<&String> = args.iter().filter(|arg_str|!arg_str.starts_with("-")).collect();
if command.len() < 3 {
return Err("not enough arguments");
}
let query = command[1].clone();
let file_path = command[2].clone();
// 查询是否忽略大小写
// 优先找环境变量 IGNORE_CASE
// 没有 IGNORE_CASE 环境变量,再查找命令行参数
let ignore_case = match env::var("IGNORE_CASE") {
Ok(flag) => flag != "0",
Err(_) => args.iter().any(|v| v == "-i" || v == "--ignore_case"),
};
Ok(Config{query, file_path, ignore_case})
}
} |
Beta Was this translation helpful? Give feedback.
-
大佬们给点改进建议
|
Beta Was this translation helpful? Give feedback.
-
交个作业。感觉写得不够Rusty,请大佬们指教! /// Some variables
pub struct Config {
pub query: String,
pub file_path: String,
pub ignore_case: bool,
}
impl Config {
// 'new' can not failed, use 'from/build' instead
pub fn from(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
// let query = args[1].clone();
// let file_path = args[2].clone();
let (query, file_path) = Self::get_query_and_file_path(args);
// let ignore_case = env::var("IGNORE_CASE").map_or(false, |var| var.eq("1"));
let ignore_case = Self::check_env("IGNORE_CASE")
|| Self::check_options(args, &[String::from("-i"), String::from("--ignore-case")]);
Ok(Config {
query,
file_path,
ignore_case,
})
}
/// query: the first non-option argument
/// file_path: the second non-option argument
pub fn get_query_and_file_path(args: &[String]) -> (String, String) {
let mut query = String::new();
let mut file_path = String::new();
for arg in &args[1..] {
if Self::is_option(arg) {
continue;
}
if query.is_empty() {
query = String::from(arg);
} else {
file_path = String::from(arg);
break;
}
}
(query, file_path)
}
/// Options are longer than 1 with - prefix
/// Example: -i --ignore-case
pub fn is_option(arg: &str) -> bool {
arg.len() > 1 && &arg[..1] == "-"
}
/// Check whether specific arguments exist or not
pub fn check_options(args: &[String], targets: &[String]) -> bool {
for target in targets {
if args[1..].contains(target) {
return true;
}
}
false
}
// TODO:
/// Check options and get there values, reture key-values
pub fn check_options_and_get_value(_target: &str) -> Option<HashMap<String, String>> {
todo!()
}
/// Environment Varibles
/// Return true if it is not empty or non-zero
pub fn check_env(variable: &str) -> bool {
let flag = env::var(variable).ok();
!matches!(flag.as_ref().map(String::as_ref), None | Some("0"))
}
} |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
let ignore_case = match env::var("IGNORE_CASE") { |
Beta Was this translation helpful? Give feedback.
-
//命令行优先 |
Beta Was this translation helpful? Give feedback.
-
课后小组业~ (在迭代器中处理逻辑) impl Config {
const IS_SENSITIVE: &str = "SENSITIVE";
pub fn build(args: &Vec<String>) -> Result<Self, &'static str> {
if args.len() != 3 {
return Err("params must equal 2!");
}
// 只要是设置了非0值, 我都认为大小写敏感
let is_sensitive = match env::var(Self::IS_SENSITIVE) {
Ok(v) if !v.eq("0") => true,
_ => false,
};
Ok(Config {
query: args[1].clone(),
file_path: args[2].clone(),
is_sensitive,
})
}
}
pub fn search<'a>(query: &str, content: &'a str, is_sensitive: bool) -> Vec<&'a str> {
content
.lines()
.into_iter()
.filter(|&x| {
let x = match is_sensitive {
true => x.to_string(),
false => x.to_lowercase(),
};
x.contains(query)
})
.collect()
} |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
我也来一个小作业答案,直接一次赋值,优先匹配环境变量: impl Config {
pub fn new(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
let ignore_case;
ignore_case = if let Some(var) = env::var("IGNORE_CASE").ok() {
var == "1" || var.to_lowercase() == "true"
} else {
if let Some(_ignore_case) = args.get(3) {
_ignore_case.as_str() == "-i"
} else {
false
}
};
println!("ignore: {ignore_case}");
Ok(Config { query, file_path, ignore_case })
}
} |
Beta Was this translation helpful? Give feedback.
-
basic-practice/envs
https://course.rs/basic-practice/envs.html
Beta Was this translation helpful? Give feedback.
All reactions