From 5b605b204d982b98af8aba3037bfadcedeeec5e6 Mon Sep 17 00:00:00 2001 From: Daiki Mizukami Date: Sun, 11 Mar 2018 10:17:25 +0900 Subject: [PATCH] Add `Value::take` method --- src/value/mod.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/value/mod.rs b/src/value/mod.rs index e05a5d6e7..de20e4d53 100644 --- a/src/value/mod.rs +++ b/src/value/mod.rs @@ -109,6 +109,7 @@ use std::fmt::{self, Debug}; use std::i64; +use std::mem; use std::str; use serde::ser::Serialize; @@ -850,7 +851,6 @@ impl Value { /// extern crate serde_json; /// /// use serde_json::Value; - /// use std::mem; /// /// fn main() { /// let s = r#"{"x": 1.0, "y": 2.0}"#; @@ -864,7 +864,7 @@ impl Value { /// assert_eq!(value.pointer("/x"), Some(&1.5.into())); /// /// // "Steal" ownership of a value. Can replace with any valid Value. - /// let old_x = value.pointer_mut("/x").map(|x| mem::replace(x, Value::Null)).unwrap(); + /// let old_x = value.pointer_mut("/x").map(Value::take).unwrap(); /// assert_eq!(old_x, 1.5); /// assert_eq!(value.pointer("/x").unwrap(), &Value::Null); /// } @@ -901,6 +901,22 @@ impl Value { } Some(target) } + + /// Takes the value out of the `Value`, leaving a `Null` in its place. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let mut v = json!({ "x": "y" }); + /// assert_eq!(v["x"].take(), json!("y")); + /// assert_eq!(v, json!({ "x": null })); + /// # } + /// ``` + pub fn take(&mut self) -> Value { + mem::replace(self, Value::Null) + } } /// The default value is `Value::Null`.