I'm trying to avoid cloning up front in the code below as in most cases the serde::from_value
will succeed. In the case where Foo
is a large object, I don't want to pay the clone cost just because every now and then the deserialization fails and I want to save the original json to permanent storage.
If serde_from_value
moves the json value I would like it back if deserialization fails. I don't see how this is possible. Does anyone have any strategies for avoiding a clone in the case where I have to accept a serde_json::Value
as an arg to convert_to_foo
?
#[derive(Debug, serde::Deserialize)]
struct Foo {
name: String
}
fn convert_to_foo(json: serde_json::Value) {
match serde_json::from_value(json) {
// ^^^^ I could clone here
Ok(foo) => save_foo_to_db(foo),
Err(_) => save_failure_to_db(json)
// ^^^^ value used here after move
}
}
fn save_foo_to_db(_foo: Foo) {
todo!();
}
fn save_failure_to_db(_json: serde_json::Value) {
todo!();
}
fn main() {
let json = serde_json::json!({ "name": "Zenora" });
convert_to_foo(json)
}