pub fn prefixed(prefix: &str) -> Prefixed<'_>Expand description
Instantiates Prefixed from which values can be both serialized and deserialized with a prefix.
The prefix is added to all keys during serialization and is expected to be present during deserialization. This is useful for namespacing environment variables to avoid conflicts.
§Examples
§Serializing with a prefix
use serde::{Serialize};
use serde_envfile::{prefixed, Error};
#[derive(Serialize)]
struct Config {
database_url: String,
port: u16,
}
fn main() -> Result<(), Error> {
let config = Config {
database_url: "postgres://localhost/mydb".to_string(),
port: 8080,
};
// Serialize with "APP_" prefix
let env_string = prefixed("APP_").to_string(&config)?;
// Results in: APP_DATABASE_URL="postgres://localhost/mydb"\nAPP_PORT="8080"
println!("{}", env_string);
Ok(())
}§Deserializing with a prefix
use serde::{Deserialize};
use serde_envfile::{prefixed, Error};
#[derive(Deserialize, Debug)]
struct Config {
database_url: String,
port: u16,
}
fn main() -> Result<(), Error> {
let env_string = "APP_DATABASE_URL=\"postgres://localhost/mydb\"\nAPP_PORT=\"8080\"";
// Deserialize with "APP_" prefix
let config: Config = prefixed("APP_").from_str(env_string)?;
assert_eq!(config.database_url, "postgres://localhost/mydb");
assert_eq!(config.port, 8080);
Ok(())
}