garde icon indicating copy to clipboard operation
garde copied to clipboard

Lifetime annotations in context structure / generic context lifetime

Open JohnstonJ opened this issue 1 year ago • 2 comments

Suppose I have a lot of data I wish to refer to in the context, so I want to use a reference. Is it possible?

Simple example:

#[derive(Debug, garde::Validate)]
#[garde(context(TestCtx as ctx))]
struct TestModel {}

struct TestCtx<'a> {
    test_ref: &'a str,
}

fails with:

error[E0106]: missing lifetime specifier
  --> crates/dv-toolbox-core/src/pack/base.rs:47:17
   |
47 | #[garde(context(TestCtx as ctx))]
   |                 ^^^^^^^ expected named lifetime parameter

Common sense suggests it should be possible, because the context shouldn't be retained after validation.

I did see the documentation states: https://docs.rs/garde/0.20.0/garde/#custom-validation

The context may be any type without generic parameters

so maybe it is currently not possible? Would it be a reasonable addition?

JohnstonJ avatar Oct 07 '24 05:10 JohnstonJ

It would require adding a generic lifetime to Validate::Context, something like https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=7c5f2d1c6b900d034dfcbdca422271b9

I'm not sure if this is something I'd want to add right now. Is there any reason why you couldn't share your data via reference counting instead?

jprochazk avatar Oct 07 '24 08:10 jprochazk

In my case, I think my actual context is small enough to copy, but yeah, reference counting would be the next thing I'd try in the current project I'm working on. I'm not blocked.

But generally speaking, I wondered if this would be a useful capability so as to avoid the reference counting alternative.

JohnstonJ avatar Oct 07 '24 09:10 JohnstonJ