Skip to content

Commit 955829c

Browse files
committed
Add documentation to write! and writeln! on using both io::Write and fmt::Write
Various existing code does this, but the documentation doesn't explain how to do it.
1 parent 69d364b commit 955829c

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
@@ -348,6 +348,21 @@ macro_rules! try {
348348
///
349349
/// assert_eq!(w, b"testformatted arguments");
350350
/// ```
351+
///
352+
/// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
353+
/// implementing either, as objects do not typically implement both. However, the module must
354+
/// import the traits qualified so their names do not conflict:
355+
///
356+
/// ```
357+
/// use std::fmt::Write as FmtWrite;
358+
/// use std::io::Write as IoWrite;
359+
///
360+
/// let mut s = String::new();
361+
/// let mut v = Vec::new();
362+
/// write!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
363+
/// write!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
364+
/// assert_eq!(v, b"s = \"abc 123\"");
365+
/// ```
351366
#[macro_export]
352367
#[stable(feature = "core", since = "1.6.0")]
353368
macro_rules! write {
@@ -391,6 +406,21 @@ macro_rules! write {
391406
///
392407
/// assert_eq!(&w[..], "test\nformatted arguments\n".as_bytes());
393408
/// ```
409+
///
410+
/// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
411+
/// implementing either, as objects do not typically implement both. However, the module must
412+
/// import the traits qualified so their names do not conflict:
413+
///
414+
/// ```
415+
/// use std::fmt::Write as FmtWrite;
416+
/// use std::io::Write as IoWrite;
417+
///
418+
/// let mut s = String::new();
419+
/// let mut v = Vec::new();
420+
/// writeln!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
421+
/// writeln!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
422+
/// assert_eq!(v, b"s = \"abc 123\\n\"\n");
423+
/// ```
394424
#[macro_export]
395425
#[stable(feature = "rust1", since = "1.0.0")]
396426
macro_rules! writeln {

0 commit comments

Comments
 (0)