Trait WriteExt

Source
pub trait WriteExt: Write {
    // Provided method
    fn write_json_lines<T, I>(&mut self, items: I) -> Result<()>
       where I: IntoIterator<Item = T>,
             T: Serialize { ... }
}
Expand description

An extension trait for the std::io::Write trait that adds a write_json_lines() method

§Example

use serde::Serialize;
use serde_jsonlines::WriteExt;
use std::fs::{read_to_string, File};
use std::io::Write;

#[derive(Serialize)]
pub struct Structure {
    pub name: String,
    pub size: i32,
    pub on: bool,
}

fn main() -> std::io::Result<()> {
    {
        let mut fp = File::create("example.jsonl")?;
        fp.write_json_lines([
            Structure {
                name: "Foo Bar".into(),
                size: 42,
                on: true,
            },
            Structure {
                name: "Quux".into(),
                size: 23,
                on: false,
            },
            Structure {
                name: "Gnusto Cleesh".into(),
                size: 17,
                on: true,
            },
        ])?;
        fp.flush()?;
    }
    // End the block to close the writer
    assert_eq!(
        read_to_string("example.jsonl")?,
        concat!(
            "{\"name\":\"Foo Bar\",\"size\":42,\"on\":true}\n",
            "{\"name\":\"Quux\",\"size\":23,\"on\":false}\n",
            "{\"name\":\"Gnusto Cleesh\",\"size\":17,\"on\":true}\n",
        )
    );
    Ok(())
}

Provided Methods§

Source

fn write_json_lines<T, I>(&mut self, items: I) -> Result<()>
where I: IntoIterator<Item = T>, T: Serialize,

Serialize each item in an iterator as a line of JSON, and write out each one followed by a newline.

All values in a single call to write_json_lines() must be the same type, but separate calls may write different types.

This method does not flush.

§Errors

Has the same error conditions as serde_json::to_writer() and std::io::Write::write_all().

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<W: Write> WriteExt for W