« Back to Index

Rust: ANSI Escape Code Clear Line

View original Gist on GitHub

Tags: #rust #ansi

ANSI Escape Code Clear Line.rs

use std::{thread::sleep, time::Duration};

const CLEAR: &str = "\x1B[2J\x1B[1;1H"; // clears the line before printing the next character

fn expensive_calculation(_n: &i32) {
    sleep(Duration::from_secs(1));
}

fn main() {
    let v: Vec<i32> = vec![1, 2, 3];
    let mut i: usize = 1;
    for n in v.iter() {
        println!("{}{}", CLEAR, "*".repeat(i));
        i += 1;
        expensive_calculation(n);
    }
}

clear line.go

// Something I noticed in a CLI tool...

func (p *InteractiveProgress) replaceLine(format string, args ...interface{}) {
	// Clear the current line.
	n := utf8.RuneCountInString(p.currentOutput)
	switch runtime.GOOS {
	case "windows":
		fmt.Fprintf(p.output, "%s\r", strings.Repeat(" ", n))
	default:
		del, _ := hex.DecodeString("7f")
		sequence := fmt.Sprintf("\b%s\b\033[K", del)
		fmt.Fprintf(p.output, "%s\r", strings.Repeat(sequence, n))
	}

	// Generate the new line.
	s := fmt.Sprintf(format, args...)
	p.currentOutput = s
	fmt.Fprint(p.output, p.currentOutput)
}