replace_all

Function replace_all 

Source
pub fn replace_all<T>(collection: &[T], old: T, new: T) -> Vec<T>
where T: PartialEq + Clone,
Expand description

Replaces all occurrences of a specified value in a collection with a new value.

This function iterates over a slice of items, replacing each occurrence of old with new. It preserves the order of elements and does not modify the original collection.

Time Complexity: O(n), where n is the number of elements in the collection.

§Arguments

  • collection - A slice of items in which to perform replacements.
  • old - The value to be replaced.
  • new - The value to replace with.

§Type Parameters

  • T - The type of elements in the collection. Must implement PartialEq and Clone.

§Returns

  • Vec<T> - A new vector with all specified replacements made.

§Examples

use lowdash::replace_all;

let numbers = vec![1, 2, 2, 3, 4, 2, 5];
let result = replace_all(&numbers, 2, 9);
assert_eq!(result, vec![1, 9, 9, 3, 4, 9, 5]);
use lowdash::replace_all;

#[derive(Debug, PartialEq, Clone)]
struct Person {
    name: String,
    age: u32,
}

let people = vec![
    Person { name: "Alice".to_string(), age: 25 },
    Person { name: "Bob".to_string(), age: 30 },
    Person { name: "Alice".to_string(), age: 25 },
    Person { name: "Carol".to_string(), age: 35 },
];

let dave = Person { name: "Dave".to_string(), age: 40 };
let result = replace_all(&people, people[0].clone(), dave.clone());
assert_eq!(
    result,
    vec![
        dave.clone(),
        people[1].clone(),
        dave.clone(),
        people[3].clone(),
    ]
);