to_value

Function to_value 

Source
pub fn to_value<T>(value: T) -> Result<Value, Error>
where T: Serialize,
Expand description

Convert a T into platform_value::Value which is an enum that can represent data.

§Example

use serde::Serialize;
use platform_value::platform_value;

use std::error::Error;

#[derive(Serialize)]
struct User {
    fingerprint: String,
    location: String,
}

fn compare_platform_values() -> Result<(), Box<dyn Error>> {
    let u = User {
        fingerprint: "0xF9BA143B95FF6D82".to_owned(),
        location: "Menlo Park, CA".to_owned(),
    };

    // The type of `expected` is `serde_json::Value`
    let expected = platform_value!({
        "fingerprint": "0xF9BA143B95FF6D82",
        "location": "Menlo Park, CA",
    });

    let v = platform_value::to_value(u).unwrap();
    assert_eq!(v, expected);

    Ok(())
}

§Errors

This conversion can fail if T’s implementation of Serialize decides to fail, or if T contains a map with non-string keys.

use std::collections::BTreeMap;

// The keys in this map are vectors, not strings.
let mut map = BTreeMap::new();
map.insert(vec![32, 64], "x86");

println!("{}", platform_value::to_value(map).unwrap_err());