line table in rust

To create a table in Rust, you can use the format! macro along with the println! macro to print out the table in the terminal. You can use ASCII characters such as dashes (-) and pipes (|) to separate the columns and rows of the table.

Here is an example of how to create a simple table in Rust:

main.rs
fn main() {
    // Define the headers and rows of the table
    let headers = ("Name", "Age", "City");
    let rows = [("John", 23, "New York"),
                ("Jane", 32, "Los Angeles"),
                ("Bob", 45, "Chicago")];
    
    // Create a separator line for the header and rows
    let separator = format!("{}-{}-{}",
        "-".repeat(headers.0.len() + 2),
        "-".repeat(headers.1.to_string().len() + 2),
        "-".repeat(headers.2.len() + 2));
    
    // Print out the table
    println!("{}", separator);
    println!("| {:^15} | {:^6} | {:^15} |", headers.0, headers.1, headers.2);
    println!("{}", separator);
    for row in rows.iter() {
        println!("| {:^15} | {:^6} | {:^15} |", row.0, row.1, row.2);
    }
    println!("{}", separator);
}
777 chars
23 lines

This code defines the headers and rows of the table, creates a separator line using the length of the headers, and then prints out the table using the println! macro with formatted strings. The ^ character centers the text in each column, and the | character separates the columns.

gistlibby LogSnag