我正在尝试序列化params
方法的send
参数。
fn send<T>(method: &str, params: T) -> () {
println!("{:?}", serde_json::to_string(¶ms));
// 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
的类型也可以是其他结构,而不仅仅是原始类型。
答案 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(¶ms));
// 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(¶ms));
// Rest of actual code that works with 'method' and 'params'
}
fn main() {
send::<i32>("account", 44);
send::<&str>("name", "John");
}