January 2019
Intermediate to advanced
520 pages
14h 32m
English
There are enough functions in the std::env standard module to work with environment variables. It contains the var function to read external values. This function returns a Result with a String value of the variable if it exists, or a VarError error if it doesn't exist. Add the import of the env module to your main.rs file:
use std::env;
We need to replace the following line:
let addr = ([127, 0, 0, 1], 8080).into();
Replace it with the following:
let addr = env::var("ADDRESS") .unwrap_or_else(|_| "127.0.0.1:8080".into()) .parse() .expect("can't parse ADDRESS variable");
This new code reads the ADDRESS value. If this value doesn't exist, we won't let the code throw a panic. Instead, we will replace it with the default value, ...
Read now
Unlock full access