Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adds as_number to Value #1069

Merged
merged 3 commits into from Sep 9, 2023
Merged

Conversation

chanced
Copy link
Contributor

@chanced chanced commented Sep 7, 2023

Resolves #1068 by adding as_number to Value.

@chanced
Copy link
Contributor Author

chanced commented Sep 7, 2023

/// If the `Value` is an Number, returns the associated [`Number`]. Returns None
/// otherwise.
///
/// ```
/// # use serde_json::{json, Number};
/// #
/// let v = json!({ "a": 1, "b": 2.2, "c": -3, "d": "4" });
///
/// // The number `1` is an u64.
/// assert_eq!(v["a"].as_number(), Some(&Number::from(1u64)));
///
/// // The number `2.2` is an f64.
/// assert_eq!(v["b"].as_number(), Some(&Number::from_f64(2.2).unwrap()));
///
/// // The number `-3` is an i64.
/// assert_eq!(v["c"].as_number(), Some(&Number::from(-3i64)));
///
/// // The string `"4"` is not a number.
/// assert_eq!(v["d"].as_number(), None);
///  
/// ```
pub fn as_number(&self) -> Option<&Number> {
    match self {
        Value::Number(number) => Some(number),
        _ => None,
    }
}

Copy link
Member

@dtolnay dtolnay left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@dtolnay dtolnay merged commit c308779 into serde-rs:master Sep 9, 2023
13 checks passed
@chanced
Copy link
Contributor Author

chanced commented Sep 9, 2023

woops, I just realized I made 2 copypasta mistakes in the comment.

  • "an Number" should be "a Number.
  • "The number 1 is an u64." should be "The number 1 is a u64"

I'm sorry about not catching it sooner!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

It'd be useful if Value had an as_number method
2 participants