No method named `serialize_field` found in `Result<<S as Serializer>::SerializeStruct, <S as Serializer>::Error>`

After following the serde documentation on serializing a struct

use serde::ser::{Serialize, Serializer, SerializeStruct};

#[derive(Debug, Clone)]
pub struct Message {
    pub sender_id: usize,
    pub receiver_id: usize,
    pub message: String,

impl Serialize for Message {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer
        let mut state = serializer.serialize_struct("Message", 3);
        state.serialize_field("sender_id", &self.sender_id)?;
        state.serialize_field("receiver_id", &self.receiver_id)?;
        state.serialize_field("message", &self.message)?;

I get this error

state.serialize_field("sender_id", &self.sender_id)?;
   |               ^^^^^^^^^^^^^^^ method not found in `Result<<S as Serializer>::SerializeStruct, <S as Serializer>::Error>`

error[E0599]: no method named `serialize_field` found for enum `Result` in the current scope
  --> src/

serialize_struct returns a Result; I think you want to add a ? to the first line:

let mut state = serializer.serialize_struct("Message", 3)?;
1 Like

Thank you!

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.