2017-10-18 128 views
2

我想填充一個可變變量相匹配的環境變量的結果:如何在使用嫉妒時使用匹配結果填充結構實例?

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 
}; 

回答

4

您正在調用哪一個做所有的分析和人口對你羨慕的方法。問題是,你扔掉的結果 - 這僅僅是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 
} 
+1

謝謝你這麼多,卻沒有意識到,它把它扔在該行的末尾。我嘗試了不那麼習慣的方式,但沒有阻止它,所以它仍然扔掉我猜。 – Joe

+1

@Joe要清楚的是,不是在{match}表達式之前放棄或不放棄的'{}',它是'let environment ='。 '好吧(環境)=>環境,'也可以。 (假設這就是你所說的「阻止它」) – trentcl

+0

@trentcl我明白了。是的,我注意到了大括號,並且意識到在最後一個語句中通常隱含着生鏽的返回值,所以我看到'''Ok(environment)=>'''後面有'''environment'''。謝謝! – Joe