Skip to content

Path::with_extension: show that it adds an extension where one did no… #141477

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 29, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions library/std/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2739,15 +2739,30 @@ impl Path {
/// # Examples
///
/// ```
/// use std::path::{Path, PathBuf};
/// use std::path::Path;
///
/// let path = Path::new("foo.rs");
/// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt"));
/// assert_eq!(path.with_extension("txt"), Path::new("foo.txt"));
/// assert_eq!(path.with_extension(""), Path::new("foo"));
/// ```
///
/// Handling multiple extensions:
///
/// ```
/// use std::path::Path;
///
/// let path = Path::new("foo.tar.gz");
/// assert_eq!(path.with_extension(""), PathBuf::from("foo.tar"));
/// assert_eq!(path.with_extension("xz"), PathBuf::from("foo.tar.xz"));
/// assert_eq!(path.with_extension("").with_extension("txt"), PathBuf::from("foo.txt"));
/// assert_eq!(path.with_extension("xz"), Path::new("foo.tar.xz"));
/// assert_eq!(path.with_extension("").with_extension("txt"), Path::new("foo.txt"));
/// ```
///
/// Adding an extension where one did not exist:
///
/// ```
/// use std::path::Path;
///
/// let path = Path::new("foo");
/// assert_eq!(path.with_extension("rs"), Path::new("foo.rs"));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
Expand Down
Loading