Keyboard shortcuts

Press ← or β†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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;
}
}
  • with can be used for methods that copy a value, but then change a specific part of that value.

    In the example here, with_extension copies the data of a &Path into a new PathBuf, but changes the extension to something else.

    The original Path is unchanged.