0

Sorry if this is a noob question.

I've created a .cargo/config.toml file in my project and configured some env variables like so:

[env]
GAME_ZERO_LEVEL = "0"
GAME_ZERO_MULTIPLIER = "0.1"
GAME_ONE_LEVEL = "1"
GAME_ONE_MULTIPLIER = "1.0"
GAME_TWO_LEVEL = "2"
GAME_TWO_MULTIPLIER = "2.5"
GAME_THREE_LEVEL = "3"
GAME_THREE_MULTIPLIER = "5.0"
GAME_FOUR_LEVEL = "4"
GAME_FOUR_MULTIPLIER = "10.0"

I will parse these into u32 and f32.

Anyway, I'm able to fetch these individually with

let value = option_env!("GAME_ZERO_LEVEL").unwrap();

Here is the problem, I want to fetch all env variables in a loop like so:


let env_keys: Vec<&str> = vec![
    "GAME_ZERO_LEVEL",
    "GAME_ZERO_MULTIPLIER",
    "GAME_ONE_LEVEL",
    "GAME_ONE_MULTIPLIER",
    "GAME_TWO_LEVEL",
    "GAME_TWO_MULTIPLIER",
    "GAME_THREE_LEVEL",
    "GAME_THREE_MULTIPLIER",
    "GAME_FOUR_LEVEL",
    "GAME_FOUR_MULTIPLIER",
];

env_keys.iter().for_each(|key| {
    let value = option_env!(key).unwrap();        //error here
    // do some stuff with it
}

But I get the following compile error rustc: argument must be a string literal

Safe to say, Im pretty confused as my previous understanding was that &str are string literals, and that passing in a &str in a variable doesnt't work. Any help understanding this would be much appreciated!

Note: I cant use std::env::{var, vars}

TLS
  • 31
  • 4
  • What you might need is [`dotenv`](https://docs.rs/dotenv/latest/dotenv/) which works outside of the `cargo` environment. – tadman Dec 31 '22 at 00:47
  • If you need to read the environment variables at compile-time, this can be achieved with a macro: [playground](https://play.rust-lang.org/?version=stable&mode=release&edition=2021&gist=e4d408b85b98fe5cd320b98670ee160b). – Jmb Dec 31 '22 at 08:49
  • This worked amazingly, thank you/q – TLS Jan 01 '23 at 01:23

1 Answers1

0

Slight misconception there &str or more specifically &'static stris the type of string literals but string literals are just the ones you type literally like this: "this is a string literal", or this r"I'm a raw string literal" or even like this r#"I'm a raw string literal which can contain " wherever"#. Everything else is not a literal. Things that are not string literals also can have that type though.

Compare also string literals in Rust by example and the reference

option_env!() evaluates it's contents at compile time so you can't use it with runtime variables like your key.

cafce25
  • 15,907
  • 4
  • 25
  • 31