Skip to content

Commit

Permalink
Merge pull request #421 from dmizuk/value-take
Browse files Browse the repository at this point in the history
Add `Value::take` method
  • Loading branch information
dtolnay authored Mar 11, 2018
2 parents aa63c93 + 5b605b2 commit 8ccbfe4
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/value/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@
use std::fmt::{self, Debug};
use std::i64;
use std::mem;
use std::str;

use serde::ser::Serialize;
Expand Down Expand Up @@ -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}"#;
Expand All @@ -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);
/// }
Expand Down Expand Up @@ -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`.
Expand Down

0 comments on commit 8ccbfe4

Please sign in to comment.