# Rust write! and writeln! - format into strings, files, and buffers

> Use Rust write! and writeln! to format directly into String buffers, byte writers, files, sockets, and other write_fmt destinations.

HTML: https://rustprint.com/output/write-and-writeln/

Use `write!` or `writeln!` when you want Rust formatting to go directly into a destination you already have, such as a `String`, file, socket, or byte buffer. `writeln!` adds a newline; `write!` does not.

**Writing formatted text into a String buffer**

```rust
use std::fmt::Write;

let mut output = String::new();
write!(&mut output, "value={}", 42).unwrap();
writeln!(&mut output, ", hex={:#x}", 42).unwrap();
assert_eq!(output, "value=42, hex=0x2a\n");
```

## Write formatted text into an existing destination

The macros work with values that provide `write_fmt`, typically through one of two traits:

- `std::fmt::Write` for Unicode text destinations such as `String`
- `std::io::Write` for byte-oriented destinations such as files, sockets, and byte buffers

For a `String`, bring `std::fmt::Write` into scope. For an I/O writer, bring `std::io::Write` into scope.

## write! vs writeln!

`write!` writes only the formatted content. `writeln!` also appends a newline.

Both return the result produced by the destination's `write_fmt` method. That is commonly `fmt::Result` for formatting destinations or `io::Result` for I/O destinations, so application code can propagate a real write failure instead of panicking through `print!`.

## Avoid the intermediate allocation

Writing directly into an existing destination avoids first building a separate `String`. By contrast, `format!` creates an owned string and the program still has to write that string somewhere afterward.

`format!` is useful when you actually need ownership of the finished string; `write!` is cleaner when the destination already exists.

For the allocation boundary, see [format!](/output/format-macro/index.md) and [format_args!](/output/format-args/index.md).

## Sources

- [write!](https://doc.rust-lang.org/std/macro.write.html)
- [writeln!](https://doc.rust-lang.org/std/macro.writeln.html)

## Related RustPrint guides

- [Rust output macros: print!, eprintln!, write!, and format!](/output/output-macros/index.md): Choose the right Rust output macro for stdout, stderr, an owned String, or an existing writer, including newline, flushing, and buffering behavior.
- [format! - build a String](/output/format-macro/index.md): Use Rust format! when you need an owned String produced with the standard formatting syntax.
- [Rust formatting traits - Display, Debug, hex, binary, and more](/reference/formatting-traits/index.md): Map Rust format syntax such as {}, {:?}, {:x}, {:b}, and {:e} to the std::fmt traits Display, Debug, LowerHex, Binary, and LowerExp.
