Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lifetime annotations in context structure / generic context lifetime #130

Open
JohnstonJ opened this issue Oct 7, 2024 · 2 comments
Open

Comments

@JohnstonJ
Copy link

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?

@jprochazk
Copy link
Owner

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?

@JohnstonJ
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants