Function try_exe_dir

Source
pub fn try_exe_dir() -> Result<&'static Path, AppPathError>
Expand description

Get the executable’s directory (fallible).

Use this only for libraries or specialized applications. Most applications should use exe_dir() for simpler, cleaner code.

§Examples

use app_path::try_exe_dir;

// Library with graceful error handling
match try_exe_dir() {
    Ok(exe_dir) => {
        println!("Executable directory: {}", exe_dir.display());
        let config = exe_dir.join("config.toml");
    }
    Err(e) => {
        eprintln!("Failed to get executable directory: {e}");
        // Implement fallback strategy
    }
}

// Use with ? operator
fn get_config_dir() -> Result<std::path::PathBuf, Box<dyn std::error::Error>> {
    let exe_dir = try_exe_dir()?;
    Ok(exe_dir.join("config"))
}

Once the executable directory is successfully determined by either this function or exe_dir(), the result is cached globally and all subsequent calls to both functions will use the cached value. This means that after the first successful call, try_exe_dir() will never return an error.

§Returns

  • Ok(&'static Path) - The directory containing the current executable
  • Err(AppPathError) - Failed to determine executable location

§Errors

Returns AppPathError if the executable location cannot be determined:

These errors represent unrecoverable system failures that occur at application startup. After the first successful call, the executable directory is cached and this function will never return an error.

§Performance

This function is highly optimized:

  • First call: Determines and caches the executable directory
  • Subsequent calls: Returns the cached result immediately (no system calls)
  • Thread-safe: Safe to call from multiple threads concurrently

§Examples

§Library Error Handling

use app_path::try_exe_dir;

// Handle the error explicitly
match try_exe_dir() {
    Ok(exe_dir) => {
        println!("Executable directory: {}", exe_dir.display());
        // Use exe_dir for further operations
    }
    Err(e) => {
        eprintln!("Failed to get executable directory: {e}");
        // Implement fallback strategy
    }
}

§Use with ? Operator

use app_path::try_exe_dir;

// Use with the ? operator in functions that return Result
fn get_config_dir() -> Result<std::path::PathBuf, Box<dyn std::error::Error>> {
    let exe_dir = try_exe_dir()?;
    Ok(exe_dir.join("config"))
}