Idiomatic way to construct Json::Null

#1

A Json type is defined as,

#[derive(Clone,PartialEq,PartialOrd)]
pub enum Json {
    Null,
    Bool(bool),
    Integer(i128),
    Float(f64),
    String(String),
    Array(Vec<Json>),
    Object(Vec<KeyValue>),
}

Subsequently, Json value constructor is implemented as

impl Json {
    pub fn new<T>(value: Option<T>) -> Json where Self : From<T> {
        match value { Some(value) => value.into(), None => Json::Null }
    }
}

From trait is implemented for all T that is wrapped inside the enum-variants.
Option is used so that Json::new(None) should return Json::Null.

But passing Json::new(None) throws up the error:

error[E0283]: type annotations required: cannot resolve `json::Json: std::convert::From<_>`
  --> src/json_test.rs:11:16
     |
     11 |     assert_eq!(Json::new(None), Json::Null);

What is the idiomatic way to solve this problem ?

0 Likes

#2

You could just say Json::Null, because it is an enum. If you really want to use the function you could use the turbofish syntax to specify a dummy type like this:

Json::new::<bool>(None)
// or
Json::new(None::<bool>)
2 Likes