• ᴥ •つ TOP

There's no rust specific code to clear the terminal screen; however, we can use ANSI codes or ANSI escape sequences. The most of the recent terminal emulators should support ANSI codes, which means we can use it in Windows, Linux, and macOS.

To clear the terminal in rust, print the following escape sequences:

print!("\x1B[2J"); println!("Hello, World");

This will clear the screen and position Hello, World on the bottom-left.

If you want to position the content right at the top after clearing the terminal, add \x1b[1;1H.

print!("\x1B[2J\x1b[1;1H"); println!("Hello, World");

You may be wondering what all those characters mean. Here are some common ANSI codes and their functions:

  1. Cursor positioning
    • \x1b[<line>;<column>H or \x1b[<line>;<column>f
  2. Clearing the screen
    • \x1b[2J - clears the screen
    • \x1b[H\x1b[J - moves the cursor to the top-left corner and clears the entire screen
  3. Text formatting
    • \x1b[<code>m - sets the text formatting attribute
    • code 0 - reset all attributes to default
    • code 1 - bold
    • code 3 - italic
    • code 4 - underline
    • code 30-37 - set foreground color (0 = black, 1 = red, ...)
← prev postnext post →