我想用匹配环境变量的结果填充一个可变变量:
struct Environment {
some_env_variable_1: String,
some_env_variable_2: String,
some_env_variable_3: String,
some_env_variable_4: String,
}
match envy::from_env::<Environment>() {
Ok(environment) => println!("{:#?}", environment),
Err(error) => panic!("{:#?})", error),
};
//where I'm stuck
let mut e = Environment {
some_env_variable_1: // want this to be from match
};
答案 0 :(得分:4)
您正在调用envy方法,它为您完成所有解析和填充。问题是你丢弃了结果 - 它只能在match
内找到:
match envy::from_env::<Environment>() {
Ok(environment) => println!("{:#?}", environment), // gone now
Err(error) => panic!("{:#?})", error),
};
你不需要扔掉它:
let environment = match envy::from_env::<Environment>() {
Ok(environment) => {
println!("{:#?}", environment);
environment // Now the entire `match` evaluates to `environment`
}
Err(error) => panic!("{:#?})", error),
};
或者,更具惯用性,只需使用expect
:
let environment: Environment = envy::from_env()
.expect("Couldn't parse environment");
println!("{:#?}", environment);
完整示例:
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate envy;
#[derive(Debug, Deserialize)]
struct Environment {
username: String,
port: u16,
}
fn main() {
let mut environment: Environment = envy::from_env()
.expect("Couldn't parse environment variables");
println!("{:#?}", environment);
}
$ USERNAME=overflow PORT=8787 cargo run
Environment {
username: "overflow",
port: 8787
}