serde-rs / json

Strongly typed JSON library for Rust
Apache License 2.0
4.7k stars 536 forks source link

Writing to fmt::Formatter #1137

Open asokol123 opened 1 month ago

asokol123 commented 1 month ago

Is it possible to serialize a value directly to fmt::Formatter? Usecase:

impl<T: Debug + serde::Serialize> Debug for Formattable<T> {
    fn fmt(&self, mut f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.format_type {
            FormatType::Json => serde_json::to_writer(f, &self.data).map_err(|e| std::fmt::Error),
            FormatType::Plain => write!(f, "{:?}", self.data),
        }
    }
}

This doesn't work because to_writer requires std::io::Write, which we can't get from std::fmt::Formatter