# query.QueryIteratorExt.matching

- **Module:** query
- **Package:** libtmux
- **Language:** Rust
- **Kind:** method
- **Source:** https://github.com/libtmux/libtmux-rs/blob/84de9258a07d10bdd5f6da01b016a9ae06fe1210/crates/libtmux/src/query.rs#L524
- **Page:** https://libtmux.org/en/rs/latest/reference/query-queryiteratorext-matching/

```
#[allow(clippy::module_name_repetitions)]
pub trait QueryIteratorExt: Iterator + Sized
fn matching<'a, T: 'a, M: Matcher<T>>(
    self,
    matcher: M
) -> impl Iterator<Item = &'a T>
where
    Self: Iterator<Item = &'a T>,
```

Lazily yield candidates accepted by `matcher`.

## Examples

```rust
use libtmux::query::{Matcher, QueryIteratorExt};

struct IsEven;

impl Matcher<i32> for IsEven {
    fn matches(&self, candidate: &i32) -> bool {
        candidate % 2 == 0
    }
}

let values = [1, 2, 3, 4];
let selected = values.iter().matching(IsEven).copied().collect::<Vec<_>>();
assert_eq!(selected, [2, 4]);
```

Filter snapshots with typed fields. Match a session name prefix without changing the source snapshot. Use a Unix environment with Git, rustup, and tmux 3.3a or newer. The toolchain file below pins Rust 1.97.1. In an empty directory, fetch the documented source:

```console
$ git clone https://github.com/libtmux/libtmux-rs.git libtmux-source &&
  git -C libtmux-source checkout --detach 84de9258a07d10bdd5f6da01b016a9ae06fe1210
```

Save this complete consumer setup as Cargo.toml:

[Source example](https://github.com/libtmux/libtmux-rs/blob/84de9258a07d10bdd5f6da01b016a9ae06fe1210/crates/libtmux/examples/api/consumer.toml).

```toml
[package]
name = "libtmux-api-example"
version = "0.0.0"
edition = "2024"
publish = false

[workspace]
exclude = ["libtmux-source"]

[dependencies]
libtmux = { path = "libtmux-source/crates/libtmux" }
tempfile = "3.20"
tokio = { version = "1.40", features = ["macros", "rt", "time"] }
```

Save this complete consumer setup as rust-toolchain.toml:

[Source example](https://github.com/libtmux/libtmux-rs/blob/84de9258a07d10bdd5f6da01b016a9ae06fe1210/rust-toolchain.toml).

```toml
[toolchain]
channel = "1.97.1"
components = ["clippy", "rust-src", "rustfmt"]
profile = "minimal"
```

Save this complete program as src/main.rs. It owns a private tmux socket, applies a ten-second task deadline, and reports both task and cleanup errors. Server::kill stops its daemon; Server::shutdown closes its client executor. Successful cleanup removes the temporary directory even when the task fails.

[Source example](https://github.com/libtmux/libtmux-rs/blob/84de9258a07d10bdd5f6da01b016a9ae06fe1210/crates/libtmux/examples/api_query.rs).

```rust
//! Filter native snapshots with typed field expressions.

use std::error::Error;
use std::time::Duration;

use libtmux::query::{Filterable as _, QueryIteratorExt as _};
use libtmux::{NewSessionOptions, Server, Session};

type ExampleError = Box<dyn Error>;

fn check(condition: bool, message: &str) -> Result<(), ExampleError> {
    if condition {
        Ok(())
    } else {
        Err(message.into())
    }
}

async fn demonstrate(server: &Server) -> Result<(), ExampleError> {
    server
        .new_session(NewSessionOptions::new("prod-api").command("cat"))
        .await?;
    server
        .new_session(NewSessionOptions::new("dev-api").command("cat"))
        .await?;
    let sessions = server.sessions().await?;
    let fields = Session::filter_fields();
    let production = fields.session_name.starts_with("prod-");
    let selected = sessions.iter().matching(&production).exactly_one()?;
    check(
        selected.name().as_bytes() == b"prod-api",
        "wrong filtered session",
    )?;
    check(sessions.len() == 2, "filtering changed the source snapshot")?;
    println!("query: prod-api");
    Ok(())
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), ExampleError> {
    let root = std::path::Path::new("/tmp/libtmux-rs-dev");
    std::fs::create_dir_all(root)?;
    let directory = tempfile::Builder::new()
        .prefix("api-query-")
        .tempdir_in(root)?;
    std::fs::write(
        directory.path().join("owner"),
        std::process::id().to_string(),
    )?;
    let server = Server::builder()
        .socket_path(directory.path().join("tmux.sock"))
        .config_file("/dev/null")
        .default_timeout(Duration::from_secs(5))
        .build()?;
    let outcome = tokio::time::timeout(Duration::from_secs(10), demonstrate(&server)).await;

    // Stop the owned daemon before closing the client executor.
    let killed = server.kill().await;
    let closed = server.shutdown().await;
    let cleanup_failed = killed.is_err() || closed.is_err();
    let mut failures = Vec::new();
    match outcome {
        Ok(Ok(())) => {}
        Ok(Err(error)) => failures.push(format!("example failed: {error}")),
        Err(error) => failures.push(format!("example deadline: {error}")),
    }
    if let Err(error) = killed {
        failures.push(format!("daemon cleanup: {error}"));
    }
    if let Err(error) = closed {
        failures.push(format!("executor cleanup: {error}"));
    }
    if cleanup_failed {
        let retained = directory.keep();
        failures.push(format!("inspect retained directory {}", retained.display()));
    } else if let Err(error) = directory.close() {
        failures.push(format!("directory cleanup: {error}"));
    }
    if failures.is_empty() {
        Ok(())
    } else {
        Err(failures.join("; ").into())
    }
}
```

Copy the complete files from the pinned checkout and run the consumer. This also creates src for the displayed program. Success exits with status 0; setup, operation, deadline or cleanup failures exit unsuccessfully and print diagnostics to stderr:

```console
$ mkdir -p src &&
  cp libtmux-source/crates/libtmux/examples/api/consumer.toml Cargo.toml &&
  cp libtmux-source/rust-toolchain.toml rust-toolchain.toml &&
  cp libtmux-source/crates/libtmux/examples/api_query.rs src/main.rs &&
  cargo run --quiet
```

Expected output:

```text
query: prod-api
```

## Type parameters

- `'a`
- `T` (bound `'a`)
- `M` (bound `Matcher<T>`)

## Parameters

- `matcher` (`M`)
