Skip to content

Clear terminal screen/console in Rust

Introduction

When working with a terminal or console application, it is sometimes necessary to clear the screen to present new content to the user. In Rust, there are several ways to achieve this, each with its own advantages and disadvantages. In this blog post, we will explore three common methods for clearing the terminal screen in Rust.

Use Control Character

fn main() {
    print!("{}[2J", 27 as char);
    // or
    // print!("\x1B[2J\x1B[1;1H");
}

Use ClearScreen Lib

[dependencies]
clearscreen = "2.0.1"

clearscreen::clear().unwrap();

Use External command

Linux or macOS terminal:

std::process::Command::new("clear").status().unwrap();

In Windows terminal:

std::process::Command::new("cls").status().unwrap();

Disclaimer
  1. License under CC BY-NC 4.0
  2. Copyright issue feedback me#imzye.com, replace # with @
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No personal information is collected
  5. Partial content rewritten by AI, verified by humans
Feedback