【问题标题】:Serde_json serialize to_string with a genericSerde_json 使用泛型序列化 to_string
【发布时间】:2019-12-23 12:23:56
【问题描述】:

我正在尝试序列化 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 的类型也可以是其他结构,而不仅仅是原始类型。

【问题讨论】:

    标签: generics rust bounds serde serde-json


    【解决方案1】:

    问题在于您没有指定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");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 2013-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      相关资源
      最近更新 更多