VarError::NotUnicode
RustERRORNotableEnvironment

Environment variable contains invalid Unicode

Quick Answer

Use std::env::var_os() to get an OsString and handle non-UTF-8 paths explicitly.

What this means

std::env::var() returned NotUnicode because the value of the environment variable is not valid UTF-8.

Why it happens
  1. 1Variable set to a non-UTF-8 byte sequence (common on Unix)
  2. 2Path variable containing non-Unicode filenames

Fix

Use var_os for OS strings

Use var_os for OS strings
use std::ffi::OsString;
if let Some(val) = std::env::var_os("PATH") {
    let val: OsString = val;
    // work with OsString directly
}

Why this works

var_os() returns OsString which can hold arbitrary OS byte sequences without UTF-8 validation.

Code examples
Safe variantrust
let val = std::env::var_os("KEY").unwrap_or_default();
Sources

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Rust errors