I'm trying to create a struct like so:
pub struct MyStruct<T: Serialize + DeserializeOwned>
where
T: 'static,
{
pub field: Type,
...
pub generic_field:T
}
But I can't see how to satisfy the Deserialize. Rust emits this message:
type annotations needed: cannot satisfy `T: _::_serde::Deserialize<'de>`
cannot satisfy `T: _::_serde::Deserialize<'de>`
Here is part of output of the Deserializer derive from ra:
#[automatically_derived]
impl < 'de,T:Serialize+DeserializeOwned>_serde::Deserialize< 'de>for MyStruct<T>where T: 'static,T:_serde::Deserialize< 'de>{
fn deserialize<__D>(__deserializer:__D) -> _serde::__private::Result<Self,__D::Error>where __D:_serde::Deserializer< 'de> ,{
#[allow(non_camel_case_types)]
enum __Field {
__field0,__field1,__field2,__field3,__field4,__field5,__field6,__ignore,
}
The line it specifically complains at is:
''static,T:_serde::Deserialize< 'de>'
Any help would be appreciated!
1 Like
I expect this has probably been asked before, but I have not been able to word it in a satisfactory for google to be of much help.
You can just remove the constraints, the derive will take care of it.
#[derive(Serialize, Deserialize)]
pub struct MyStruct<T>
where
T: 'static,
{
pub field: Type,
pub generic_field: T,
}
In general, you don't need to add constraints to structs. You can just add the exact constraints you need to whatever functions or methods need them.
3 Likes
If you need to, you can add a #[serde(bound = "T: Serialize + DeserializeOwned")]
attribute to MyStruct
if you only want it to be deserialized under certain conditions.
use serde::{de::DeserializeOwned, Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
#[serde(bound = "T: Serialize + DeserializeOwned")]
struct MyStruct<T: DeserializeOwned> {
generic_field: T,
}
(playground)
1 Like
system
Closed
6
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.