Serde_json 使用通用序列化 to_string

Serde_json serialize to_string with a generic

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

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 的类型也可以是其他结构,而不仅仅是原始类型。

问题是您没有指定所有 T 都可以实现 Serialize-trait。你应该告诉编译器你只打算给它 ​​Serialize-implementors.

一个解决方案是按照编译器所说的去做:

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");
}