Serde_json使用通用序列化to_string

时间:2019-12-23 12:23:56

标签: generics rust bounds serde serde-json

我正在尝试序列化params方法的send参数。

fn send<T>(method: &str, params: T) -> () {
    println!("{:?}", serde_json::to_string(&params));
    // Rest of actual code that works with 'method' and 'params'
}

fn main() {
    send::<i32>("account", 44);
    send::<&str>("name", "John");
}

但这给了我我无法解决的以下错误:

the trait bound `T: primitives::_IMPL_DESERIALIZE_FOR_Address::_serde::Serialize` is not satisfied

the trait `primitives::_IMPL_DESERIALIZE_FOR_Address::_serde::Serialize` is not implemented for `T`

help: consider adding a `where T: primitives::_IMPL_DESERIALIZE_FOR_Address::_serde::Serialize` boundrustc(E0277)

我猜想是因为尽管我在调用send时指定了它的类型,但是它不知道需要序列化的类型。传递给params的类型也可以是其他结构,而不仅仅是原始类型。

1 个答案:

答案 0 :(得分:0)

问题是您没有指定所有T都可以实现Serialize特性。您应该告诉编译器,您仅打算将其提供给Serialize实现者​​。

一种解决方案是按照编译器的说明进行操作:

help: consider adding a `where T: primitives::_IMPL_DESERIALIZE_FOR_Address::_serde::Serialize` boundrustc(E0277)

因此,您的代码应如下所示:

fn send<T: serde::Serialize>(method: &str, params: T) -> () {
    println!("{:?}", serde_json::to_string(&params));
    // Rest of actual code that works with 'method' and 'params'
}

fn main() {
    send::<i32>("account", 44);
    send::<&str>("name", "John");
}

或使用where关键字:

fn send<T>(method: &str, params: T) -> () where T: serde::Serialize {
    println!("{:?}", serde_json::to_string(&params));
    // Rest of actual code that works with 'method' and 'params'
}

fn main() {
    send::<i32>("account", 44);
    send::<&str>("name", "John");
}