I plan to have a struct which provides the JSON schema via a trait method.
The schema is stored compiled in a lazy_static variable, but which type does my schema()
function have to return?
lazy_static::lazy_static! {
static ref DEF: serde_json::Value = serde_json::json!({
"type": "object",
"properties": {
"name": { "type": "string",
"minLength": 10,
},
},
});
static ref SCHEMA: jsonschema::JSONSchema<'static> = jsonschema::JSONSchema::compile(&DEF).unwrap();
}
struct MySchema {
name: String,
}
impl MySchema {
pub fn schema() -> jsonschema::JSONSchema<'static> {
SCHEMA
}
}
#[test]
pub fn test() {
let test = serde_json::json!({"name":"test"});
assert_eq!(SCHEMA.is_valid(&test), false);
assert_eq!(MySchema::schema().is_valid(&test), false);
}
I'll get this error
pub fn schema() -> jsonschema::JSONSchema<'static> {
------------------------------- expected `JSONSchema<'static>` because of return type
SCHEMA
^^^^^^ expected struct `JSONSchema`, found struct `SCHEMA`
I close this question with answer from Sven Marnach:
You can't return an owned value. You can only return a reference to the static variable. Change return type to
&'static jsonschema::JSONSchema<'static>
and the return value to&*SCHEMA
.