Add Value::take method

This commit is contained in:
Daiki Mizukami
2018-03-11 10:17:25 +09:00
parent aa63c9302d
commit 5b605b204d

View File

@@ -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`.