How to use text/tabwriter for column alignment in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "os"
    "text/tabwriter"
)

func main() {
    /*
        Creates a writer w that reformats text with tabs.

        Parameters:

        os.Stdout: Where to print.
        0, 0: Minimum and tab width (0 lets writer adjust).
        3: Padding between columns.
        ' ' (space): Padding character.
        0: Formatting flags.
    */
    w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
    
    fmt.Fprintln(w, "Name\tScore\t")
    fmt.Fprintln(w, "Tom\t90\t")
    fmt.Fprintln(w, "Robert\t85\t")
    fmt.Fprintln(w, "Jennifer\t100\t")
    
    // Forces the tabwriter to process and write the aligned text to os.Stdout
    w.Flush()
}



/*
run:

Name       Score   
Tom        90      
Robert     85      
Jennifer   100  

*/

 



answered Jul 3, 2025 by avibootz
...