0

I'm trying to use Rust's config crate to handle a config struct that includes a field with type Vec<String>. I can define my struct and everything compiles, but I can't seem to set the value using an environment variable - it seems like the default environment variable deserialization treats my input as a single string rather than a Vec, so I get the error invalid type: string "[\"a\",\"b\"]", expected a sequence.

Here's a minimal example

// Cargo.toml

[package]
name = "min_config"
version = "0.1.0"

[dependencies]
config = "0.10.1"
serde = { version = "1.0.117", features = ["derive"] }
// src/main.rs

extern crate config;
extern crate serde;

use config::{Config, ConfigError, Environment};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct MyConfig {
    pub strs: Vec<String>,
}

impl MyConfig {
    pub fn from_env() -> Result<Self, ConfigError> {
        let mut s = Config::new();
        s.merge(Environment::with_prefix("CFG"))?;
        s.try_into()
    }
}

pub fn main() {
    let cfg = MyConfig::from_env().unwrap();
}

Running the code:

$ CFG_STRS='["a","b"]' cargo run
   Compiling min_config v0.1.0 (/Users/greg/Code/rust/min_config)
    Finished dev [unoptimized + debuginfo] target(s) in 0.71s
     Running `target/debug/min_config`
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: invalid type: string "[\"a\",\"b\"]", expected a sequence', src/main.rs:21:13

How can I pass an environment variable in such a way that serde will recognize that it's a Vec<String>, not just a String?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Greg Owen
  • 947
  • 8
  • 19

1 Answers1

1

Config uses JSON for parsing files but not environment variables. Unfortunately, based on this issue, it doesn't appear there is a way to read arrays from the environment.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
kmdreko
  • 42,554
  • 6
  • 57
  • 106