Skip to content

Commit e10e49d

Browse files
authored
Rollup merge of rust-lang#37472 - joshtriplett:doc-fmt-write-io-write, r=brson
Document convention for using both fmt::Write and io::Write Using a trait's methods (like `Write::write_fmt` as used in `writeln!` and other macros) requires importing that trait directly (not just the module containing it). Both `fmt::Write` and `io::Write` provide compatible `Write::write_fmt` methods, and code can use `writeln!` and other macros on both an object implementing `fmt::Write` (such as a `String`) and an object implementing `io::Write` (such as `Stderr`). However, importing both `Write` traits produces an error due to the name conflict. The convention I've seen renames both of them on import, to `FmtWrite` and `IoWrite` respectively. Document that convention in the Rust documentation for `write!` and `writeln!`, with examples.
2 parents d712882 + 955829c commit e10e49d

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/libcore/macros.rs

+30
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,21 @@ macro_rules! try {
350350
///
351351
/// assert_eq!(w, b"testformatted arguments");
352352
/// ```
353+
///
354+
/// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
355+
/// implementing either, as objects do not typically implement both. However, the module must
356+
/// import the traits qualified so their names do not conflict:
357+
///
358+
/// ```
359+
/// use std::fmt::Write as FmtWrite;
360+
/// use std::io::Write as IoWrite;
361+
///
362+
/// let mut s = String::new();
363+
/// let mut v = Vec::new();
364+
/// write!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
365+
/// write!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
366+
/// assert_eq!(v, b"s = \"abc 123\"");
367+
/// ```
353368
#[macro_export]
354369
#[stable(feature = "core", since = "1.6.0")]
355370
macro_rules! write {
@@ -394,6 +409,21 @@ macro_rules! write {
394409
///
395410
/// assert_eq!(&w[..], "test\nformatted arguments\n".as_bytes());
396411
/// ```
412+
///
413+
/// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
414+
/// implementing either, as objects do not typically implement both. However, the module must
415+
/// import the traits qualified so their names do not conflict:
416+
///
417+
/// ```
418+
/// use std::fmt::Write as FmtWrite;
419+
/// use std::io::Write as IoWrite;
420+
///
421+
/// let mut s = String::new();
422+
/// let mut v = Vec::new();
423+
/// writeln!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
424+
/// writeln!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
425+
/// assert_eq!(v, b"s = \"abc 123\\n\"\n");
426+
/// ```
397427
#[macro_export]
398428
#[stable(feature = "rust1", since = "1.0.0")]
399429
macro_rules! writeln {

0 commit comments

Comments
 (0)