Use of OnceLock instead of lazy_static in regex validator.
your-diary opened this issue · 2 comments
your-diary commented
regex
validator takes a static Regex
instance.
This used to be created via an external crate such as lazy_static
.
However, in modern Rust, recently added std::sync::OnceLock
is often used for that purpose (though lazy_static
is still widely used.)
Is it possible to pass OnceLock
to regex
validator?
lazy_static
use lazy_static::lazy_static;
use regex::Regex;
use serde::{Deserialize, Serialize};
use validator::Validate;
lazy_static! {
static ref REGEX: Regex = Regex::new(r#"e$"#).unwrap();
}
#[derive(Debug, Deserialize, Serialize, Validate)]
struct S {
#[validate(regex = "REGEX")]
name: String,
}
impl S {
fn new(json_string: &str) -> Self {
serde_json::from_str(json_string).unwrap()
}
}
fn main() {
let json_string = r#"
{
"name": "Mike"
}
"#;
let s = S::new(json_string);
assert!(s.validate().is_ok());
}
OnceLock
(doesn't compile)
use std::sync::OnceLock;
use regex::Regex;
use serde::{Deserialize, Serialize};
use validator::Validate;
static REGEX: OnceLock<Regex> = OnceLock::new();
#[derive(Debug, Deserialize, Serialize, Validate)]
struct S {
#[validate(regex = "REGEX")]
name: String,
}
impl S {
fn new(json_string: &str) -> Self {
serde_json::from_str(json_string).unwrap()
}
}
fn main() {
REGEX.set(Regex::new(r#"e$"#).unwrap());
let json_string = r#"
{
"name": "Mike"
}
"#;
let s = S::new(json_string);
assert!(s.validate().is_ok());
}