简体   繁体   English

如何在Rust中合并来自不同库的类型?

[英]How to combine types from different libraries in Rust?

I am using the the Rust libraries swtweb (to interface with JavaScript) and serde-json (to work with JSON). 我正在使用Rust库swtweb (用于与JavaScript交互)和serde-json (用于JSON)。 Both have a Value type to represent JavaScript objects that are very similar: 两者都有一个Value类型来表示非常相似的JavaScript对象:

swtweb's Value : swtweb的Value

#[derive(Clone, PartialEq, Debug)]
pub enum Value {
    Undefined,
    Null,
    Bool(bool),
    Number(Number),
    Symbol(Symbol),
    String(String),
    Reference(Reference)
}

and serde-json's Value : serde-json的Value

#[derive(Clone, PartialEq)]
pub enum Value {
    Null,
    Bool(bool),
    Number(Number),
    String(String),
    Array(Vec<Value>),
    Object(Map<String, Value>),
}

What is an approach to transform instances of one type to another? 将一种类型的实例转换为另一种类型的方法是什么? Is it possible to derive a common trait without modifying the libraries? 是否可以在不修改库的情况下得出共同的特征?

Looking at the doc of stdweb::Value , it seems they have you covered! 查看stdweb::Value的文档,看来它们已经覆盖了您!

It implements TryFrom<JsonValue> , with JsonValue being an alias of serde_json::Value , so this lets you converts from serde_json::Value to stdweb::Value . 它实现了TryFrom<JsonValue> ,其中JsonValueserde_json::Value的别名,因此,您可以从serde_json::Value转换为stdweb::Value

It implements Serialize , and serde_json::to_value lets you convert any type that implements Serialize to a serde_json::Value 它实现了Serialize ,而serde_json::to_value允许您将实现Serialize任何类型转换为serde_json::Value

So this should work: 所以这应该工作:

let json_value: serde_json::Value = json!("my value");
println!("{:#?}", json_value);

let stdweb_value: stdweb::Value = stdweb::Value::try_from(json_value).unwrap();
println!("{:#?}", stdweb_value);

let json_value_again: serde_json::Value = serde_json::to_value(stdweb_value).unwrap();
println!("{:#?}", json_value_again);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM