Black Lives Matter. Support the Equal Justice Initiative.

Source file src/text/tabwriter/example_test.go

Documentation: text/tabwriter

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package tabwriter_test
     6  
     7  import (
     8  	"fmt"
     9  	"os"
    10  	"text/tabwriter"
    11  )
    12  
    13  func ExampleWriter_Init() {
    14  	w := new(tabwriter.Writer)
    15  
    16  	// Format in tab-separated columns with a tab stop of 8.
    17  	w.Init(os.Stdout, 0, 8, 0, '\t', 0)
    18  	fmt.Fprintln(w, "a\tb\tc\td\t.")
    19  	fmt.Fprintln(w, "123\t12345\t1234567\t123456789\t.")
    20  	fmt.Fprintln(w)
    21  	w.Flush()
    22  
    23  	// Format right-aligned in space-separated columns of minimal width 5
    24  	// and at least one blank of padding (so wider column entries do not
    25  	// touch each other).
    26  	w.Init(os.Stdout, 5, 0, 1, ' ', tabwriter.AlignRight)
    27  	fmt.Fprintln(w, "a\tb\tc\td\t.")
    28  	fmt.Fprintln(w, "123\t12345\t1234567\t123456789\t.")
    29  	fmt.Fprintln(w)
    30  	w.Flush()
    31  
    32  	// output:
    33  	// a	b	c	d		.
    34  	// 123	12345	1234567	123456789	.
    35  	//
    36  	//     a     b       c         d.
    37  	//   123 12345 1234567 123456789.
    38  }
    39  
    40  func Example_elastic() {
    41  	// Observe how the b's and the d's, despite appearing in the
    42  	// second cell of each line, belong to different columns.
    43  	w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, '.', tabwriter.AlignRight|tabwriter.Debug)
    44  	fmt.Fprintln(w, "a\tb\tc")
    45  	fmt.Fprintln(w, "aa\tbb\tcc")
    46  	fmt.Fprintln(w, "aaa\t") // trailing tab
    47  	fmt.Fprintln(w, "aaaa\tdddd\teeee")
    48  	w.Flush()
    49  
    50  	// output:
    51  	// ....a|..b|c
    52  	// ...aa|.bb|cc
    53  	// ..aaa|
    54  	// .aaaa|.dddd|eeee
    55  }
    56  
    57  func Example_trailingTab() {
    58  	// Observe that the third line has no trailing tab,
    59  	// so its final cell is not part of an aligned column.
    60  	const padding = 3
    61  	w := tabwriter.NewWriter(os.Stdout, 0, 0, padding, '-', tabwriter.AlignRight|tabwriter.Debug)
    62  	fmt.Fprintln(w, "a\tb\taligned\t")
    63  	fmt.Fprintln(w, "aa\tbb\taligned\t")
    64  	fmt.Fprintln(w, "aaa\tbbb\tunaligned") // no trailing tab
    65  	fmt.Fprintln(w, "aaaa\tbbbb\taligned\t")
    66  	w.Flush()
    67  
    68  	// output:
    69  	// ------a|------b|---aligned|
    70  	// -----aa|-----bb|---aligned|
    71  	// ----aaa|----bbb|unaligned
    72  	// ---aaaa|---bbbb|---aligned|
    73  }
    74  

View as plain text