Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example to IsTerminal::is_terminal #124992

Merged
merged 1 commit into from
May 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions library/std/src/io/stdio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1161,7 +1161,41 @@ pub trait IsTerminal: crate::sealed::Sealed {
/// starting with `msys-` or `cygwin-` and ending in `-pty` will be considered terminals.
/// Note that this [may change in the future][changes].
///
/// # Examples
///
/// An example of a type for which `IsTerminal` is implemented is [`Stdin`]:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It'd be great, though not essential, to have an example that includes both Stdin and Stdout.

///
/// ```no_run
/// use std::io::{self, IsTerminal, Write};
///
/// fn main() -> io::Result<()> {
/// let stdin = io::stdin();
///
/// // Indicate that the user is prompted for input, if this is a terminal.
/// if stdin.is_terminal() {
/// print!("> ");
/// io::stdout().flush()?;
/// }
///
/// let mut name = String::new();
/// let _ = stdin.read_line(&mut name)?;
///
/// println!("Hello {}", name.trim_end());
///
/// Ok(())
/// }
/// ```
///
/// The example can be run in two ways:
///
/// - If you run this example by piping some text to it, e.g. `echo "foo" | path/to/executable`
/// it will print: `Hello foo`.
/// - If you instead run the example interactively by running the executable directly, it will
/// panic with the message "Expected input to be piped to the process".
///
///
/// [changes]: io#platform-specific-behavior
/// [`Stdin`]: crate::io::Stdin
#[stable(feature = "is_terminal", since = "1.70.0")]
fn is_terminal(&self) -> bool;
}
Expand Down
Loading