Skip to content

Commit 3a5f258

Browse files
authored
Rollup merge of rust-lang#124992 - foresterre:example/is-terminal, r=ChrisDenton
Add example to IsTerminal::is_terminal
2 parents 625f7c3 + 7e59233 commit 3a5f258

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Diff for: std/src/io/stdio.rs

+34
Original file line numberDiff line numberDiff line change
@@ -1161,7 +1161,41 @@ pub trait IsTerminal: crate::sealed::Sealed {
11611161
/// starting with `msys-` or `cygwin-` and ending in `-pty` will be considered terminals.
11621162
/// Note that this [may change in the future][changes].
11631163
///
1164+
/// # Examples
1165+
///
1166+
/// An example of a type for which `IsTerminal` is implemented is [`Stdin`]:
1167+
///
1168+
/// ```no_run
1169+
/// use std::io::{self, IsTerminal, Write};
1170+
///
1171+
/// fn main() -> io::Result<()> {
1172+
/// let stdin = io::stdin();
1173+
///
1174+
/// // Indicate that the user is prompted for input, if this is a terminal.
1175+
/// if stdin.is_terminal() {
1176+
/// print!("> ");
1177+
/// io::stdout().flush()?;
1178+
/// }
1179+
///
1180+
/// let mut name = String::new();
1181+
/// let _ = stdin.read_line(&mut name)?;
1182+
///
1183+
/// println!("Hello {}", name.trim_end());
1184+
///
1185+
/// Ok(())
1186+
/// }
1187+
/// ```
1188+
///
1189+
/// The example can be run in two ways:
1190+
///
1191+
/// - If you run this example by piping some text to it, e.g. `echo "foo" | path/to/executable`
1192+
/// it will print: `Hello foo`.
1193+
/// - If you instead run the example interactively by running the executable directly, it will
1194+
/// panic with the message "Expected input to be piped to the process".
1195+
///
1196+
///
11641197
/// [changes]: io#platform-specific-behavior
1198+
/// [`Stdin`]: crate::io::Stdin
11651199
#[stable(feature = "is_terminal", since = "1.70.0")]
11661200
fn is_terminal(&self) -> bool;
11671201
}

0 commit comments

Comments
 (0)