assert-rs / predicates-rs

Boolean-valued predicate functions in Rust
docs.rs/predicates
Apache License 2.0
175 stars 29 forks source link

Why does `.name(str)` require a `'static` lifetime string? #150

Open demmerichs opened 1 year ago

demmerichs commented 1 year ago

I want to add names to predicates I construct inside a loop, e.g.

use predicates::{prelude::*, BoxPredicate};

fn test_predicates() {
    let gt = vec![1, 2, 3];
    let mut predicate: BoxPredicate<str> = BoxPredicate::new(predicate::always());
    for g in gt {
        let name = format!("{}", g);
        predicate = BoxPredicate::new(predicate.and(predicate::never().name(&name)));
    }
    assert!(predicate.eval("Hello World!"));
}

I expected to see this happen: Allow me to pass Strings, or &str which get cloned inside the naming.

Instead this happened: Compile Error:

   |
8  |         let name = format!("{}", g);
   |             ---- binding `name` declared here
9  |         predicate = BoxPredicate::new(predicate.and(predicate::never().name(&name)));
   |                                                     ------------------------^^^^^-
   |                                                     |                       |
   |                                                     |                       borrowed value does not live long enough
   |                                                     argument requires that `name` is borrowed for `'static`
10 |     }
   |     - `name` dropped here while still borrowed

Meta

predicates-rs version: 3.0.3 rustc --version --verbose: rustc 1.71.1 (eb26296b5 2023-08-03) binary: rustc commit-hash: eb26296b556cef10fb713a38f3d16b9886080f26 commit-date: 2023-08-03 host: x86_64-unknown-linux-gnu release: 1.71.1 LLVM version: 16.0.5

epage commented 1 year ago

Reason: a lot of the features were developed for basic test cases, like with assert_cmd and assert_fs where dynamic data isn't as needed.

That doesn't mean it can't change though it would involve a breaking change.