with as copy-and-set
with appears when a value is being copied, but also changed in a specific way.
with as in “like <value>, but with something different.”
#![allow(unused)]
fn main() {
// Copyright 2025 Google LLC
// SPDX-License-Identifier: Apache-2.0
impl Path {
// Simplified. "/home/me/mortgage.pdf".with_extension("mov") =>
// "/home/me/mortgage.mov"
fn with_extension(&self, ext: &OsStr) -> PathBuf;
}
}
-
withcan be used for methods that copy a value, but then change a specific part of that value.In the example here,
with_extensioncopies the data of a&Pathinto a newPathBuf, but changes the extension to something else.The original
Pathis unchanged.