RS.CLIPPY.SET_CONTAINS_OR_INSERT

Call to `<set>::contains` followed by `<set>::insert`

This checker is a Clippy lint created by The Rust Project Contributors. The documentation shown here is a copy of the original documentation for: set_contains_or_insert. Copyright ©2025 The Rust Team. All rights reserved.

What it does

Checks for usage of contains to see if a value is not present in a set like HashSet or BTreeSet, followed by an insert.

Why is this bad?

Using just insert and checking the returned bool is more efficient.

Known problems

In case the value that wants to be inserted is borrowed and also expensive or impossible to clone. In such a scenario, the developer might want to check with contains before inserting, to avoid the clone. In this case, it will report a false positive.

Example

use std::collections::HashSet;
let mut set = HashSet::new();
let value = 5;
if !set.contains(&value) {
    set.insert(value);
    println!("inserted {value:?}");
}

Use instead:

use std::collections::HashSet;
let mut set = HashSet::new();
let value = 5;
if set.insert(&value) {
    println!("inserted {value:?}");
}