0

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

4

1 回答 1

0

问题是您没有指定一切都T可以实现Serialize-trait。你应该告诉编译器你只打算给它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-keyword:

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");
}
于 2019-12-23T12:39:16.233 回答