Caminhos (std::path)
Nesta página
std::path é uma biblioteca de manipulação de strings; não toca o disco.
Toda função recebe e devolve strings de caminho, usando o separador correto do
sistema operacional. Para verificar se um caminho existe ou ler seu conteúdo,
use std::fs.
Unir, separar e extrair componentes
path.join monta caminhos com o separador nativo. path.dirname e
path.basename partem o caminho no último separador. path.ext e path.stem
isolam a extensão e o nome sem extensão:
Une partes com join; extrai diretório, nome-base, extensão e stem.
// Feature: path.join / path.dirname / path.basename — path manipulation
// When to use: build cross-platform paths without worrying about / vs \.
use std::path
// path.join(...) glues parts together using the right OS separator.
let p = path.join("home", "user", "docs", "file.txt")
print(p) // expected: home/user/docs/file.txt (or \ on Windows)
// path.dirname -> everything up to the last separator.
print(path.dirname("/var/log/app.log")) // expected: /var/log
// path.basename -> last component of the path.
print(path.basename("/var/log/app.log")) // expected: app.log
// path.ext / path.stem split off the extension.
print(path.ext("report.pdf")) // expected: .pdf (or pdf — depends on impl)
print(path.stem("report.pdf")) // expected: report
// path.separator is "/" on Unix and "\" on Windows.
print(path.separator()) // expected: OS separator
Absoluto, relativo e normalização
path.is_absolute / path.is_relative consultam o tipo do caminho.
path.normalize colapsa . e .. e separadores duplicados. path.resolve
retorna o caminho absoluto (usando o diretório de trabalho atual se o caminho
for relativo). path.relative(from, to) calcula o caminho relativo entre dois
pontos:
Verifica tipo, normaliza, resolve e computa caminhos relativos.
// Feature: path.is_absolute / is_relative / normalize / resolve / relative
// When to use: validate inputs, resolve relative paths, deduplicate.
use std::path
// is_absolute / is_relative — query the kind of path.
print(path.is_absolute("/etc/hosts")) // expected: true (false on Windows)
print(path.is_relative("docs/readme")) // expected: true
// normalize collapses "." and ".." and duplicate separators.
print(path.normalize("a/b/../c/./d")) // expected: a/c/d
// resolve returns the absolute path (joins with cwd if relative).
let abs = path.resolve("report.txt")
print(abs.len() > 0) // expected: true
// relative(from, to) computes the relative path from `from` to `to`.
print(path.relative("/var/log", "/var/log/app/error.log"))
// expected: app/error.log
Combinando path com fs para verificar existência
As funções de existência (exists, is_file, is_dir) pertencem a std::fs,
não a std::path. Este exemplo mostra como construir um caminho com
path.join e testá-lo com fs:
Une componentes com path.join e verifica existência com fs.exists / fs.is_file.
// Feature: path/fs — test for file existence
// When to use: validate user input, decide whether to create a file.
// Note: IO functions (`exists`, `is_file`, `is_dir`) live in the `fs` module,
// not in `path`. `path` is pure string manipulation; `fs` touches the disk.
use std::path
use std::fs
// Build the path with path.join and test with fs.exists.
let target = path.join("examples", "features", "17-stdlib", "path", "README.md")
// fs.exists(path) -> bool.
let here = fs.exists(target)
print(here) // expected: true (when running from project root)
// Other type checks:
// fs.is_file(p) — regular file
// fs.is_dir(p) — directory
print(fs.is_file(target)) // expected: true
print(fs.is_dir("examples/features")) // expected: true
Requer a CLI/host do Zolo — abra no playground ou rode localmente.
Veja também