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();
Leave a message