path_macro2
A cross-platform path construction macro for Rust that provides an intuitive syntax for building file paths while automatically handling platform-specific path separators.
Features
- Dual syntax support: Use either slash (
/) or comma (,) separators - Cross-platform: Automatically uses correct path separators (
\on Windows,/on Unix-like systems) - Variable interpolation: Support for runtime variables and expressions
- Multiple segment types: Identifiers, dotted names, string literals, and expressions
- Zero dependencies: Lightweight macro-only implementation
Installation
Add this to your Cargo.toml:
[]
= "0.1.1"
Usage
Basic Syntax
The macro supports two equivalent syntaxes:
use path;
// Slash syntax
let path1 = path!;
// Comma syntax
let path2 = path!;
// Both produce the same result:
// Windows: "vendor\dll\windivert.c"
// Unix: "vendor/dll/windivert.c"
Supported Segment Types
Identifiers and Dotted Names
let path = path!; // Simple identifiers
let file = path!; // Dotted identifiers
String Literals (for spaces and special characters)
let path = path!;
let docs = path!;
Variable Interpolation
let base = "vendor";
let version = "1.0";
// Variables wrapped in curly braces
let path = path!;
let versioned = path!;
Platform-Specific Examples
Unix/Linux Absolute Paths
let abs_path = path!;
// Result: "/usr/local/bin/myapp"
Windows Paths
// Drive letter paths
let win_path = path!;
// Result: "C:\Program Files\MyApp\app.exe"
// UNC network paths
let unc_path = path!;
// Result: "\\server\share\file.txt"
Complex Examples
use path;
How It Works
The path! macro processes path segments and automatically:
- Converts identifiers to strings:
vendorbecomes"vendor" - Handles dotted identifiers:
file.txtbecomes"file.txt" - Preserves string literals:
"my folder"stays as-is - Evaluates expressions:
{base_path}evaluates the variable - Builds PathBuf: Uses
std::path::PathBuf::push()for proper platform handling
The result is always a std::path::PathBuf that uses the correct path
separators for the target platform.
Comparison with Alternatives
| Method | Cross-platform | Readable | Variables | Compile-time |
|---|---|---|---|---|
path_macro2::path! |
✅ | ✅ | ✅ | ✅ |
std::path::Path::join() |
✅ | ❌ | ✅ | ❌ |
| String concatenation | ❌ | ❌ | ✅ | ❌ |
format!() with / |
❌ | ⚠️ | ✅ | ❌ |
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.