...

Source file src/fmt/example_test.go

Documentation: fmt

		 1  // Copyright 2017 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 fmt_test
		 6  
		 7  import (
		 8  	"fmt"
		 9  	"io"
		10  	"math"
		11  	"os"
		12  	"strings"
		13  	"time"
		14  )
		15  
		16  // The Errorf function lets us use formatting features
		17  // to create descriptive error messages.
		18  func ExampleErrorf() {
		19  	const name, id = "bueller", 17
		20  	err := fmt.Errorf("user %q (id %d) not found", name, id)
		21  	fmt.Println(err.Error())
		22  
		23  	// Output: user "bueller" (id 17) not found
		24  }
		25  
		26  func ExampleFscanf() {
		27  	var (
		28  		i int
		29  		b bool
		30  		s string
		31  	)
		32  	r := strings.NewReader("5 true gophers")
		33  	n, err := fmt.Fscanf(r, "%d %t %s", &i, &b, &s)
		34  	if err != nil {
		35  		fmt.Fprintf(os.Stderr, "Fscanf: %v\n", err)
		36  	}
		37  	fmt.Println(i, b, s)
		38  	fmt.Println(n)
		39  	// Output:
		40  	// 5 true gophers
		41  	// 3
		42  }
		43  
		44  func ExampleFscanln() {
		45  	s := `dmr 1771 1.61803398875
		46  	ken 271828 3.14159`
		47  	r := strings.NewReader(s)
		48  	var a string
		49  	var b int
		50  	var c float64
		51  	for {
		52  		n, err := fmt.Fscanln(r, &a, &b, &c)
		53  		if err == io.EOF {
		54  			break
		55  		}
		56  		if err != nil {
		57  			panic(err)
		58  		}
		59  		fmt.Printf("%d: %s, %d, %f\n", n, a, b, c)
		60  	}
		61  	// Output:
		62  	// 3: dmr, 1771, 1.618034
		63  	// 3: ken, 271828, 3.141590
		64  }
		65  
		66  func ExampleSscanf() {
		67  	var name string
		68  	var age int
		69  	n, err := fmt.Sscanf("Kim is 22 years old", "%s is %d years old", &name, &age)
		70  	if err != nil {
		71  		panic(err)
		72  	}
		73  	fmt.Printf("%d: %s, %d\n", n, name, age)
		74  
		75  	// Output:
		76  	// 2: Kim, 22
		77  }
		78  
		79  func ExamplePrint() {
		80  	const name, age = "Kim", 22
		81  	fmt.Print(name, " is ", age, " years old.\n")
		82  
		83  	// It is conventional not to worry about any
		84  	// error returned by Print.
		85  
		86  	// Output:
		87  	// Kim is 22 years old.
		88  }
		89  
		90  func ExamplePrintln() {
		91  	const name, age = "Kim", 22
		92  	fmt.Println(name, "is", age, "years old.")
		93  
		94  	// It is conventional not to worry about any
		95  	// error returned by Println.
		96  
		97  	// Output:
		98  	// Kim is 22 years old.
		99  }
	 100  
	 101  func ExamplePrintf() {
	 102  	const name, age = "Kim", 22
	 103  	fmt.Printf("%s is %d years old.\n", name, age)
	 104  
	 105  	// It is conventional not to worry about any
	 106  	// error returned by Printf.
	 107  
	 108  	// Output:
	 109  	// Kim is 22 years old.
	 110  }
	 111  
	 112  func ExampleSprint() {
	 113  	const name, age = "Kim", 22
	 114  	s := fmt.Sprint(name, " is ", age, " years old.\n")
	 115  
	 116  	io.WriteString(os.Stdout, s) // Ignoring error for simplicity.
	 117  
	 118  	// Output:
	 119  	// Kim is 22 years old.
	 120  }
	 121  
	 122  func ExampleSprintln() {
	 123  	const name, age = "Kim", 22
	 124  	s := fmt.Sprintln(name, "is", age, "years old.")
	 125  
	 126  	io.WriteString(os.Stdout, s) // Ignoring error for simplicity.
	 127  
	 128  	// Output:
	 129  	// Kim is 22 years old.
	 130  }
	 131  
	 132  func ExampleSprintf() {
	 133  	const name, age = "Kim", 22
	 134  	s := fmt.Sprintf("%s is %d years old.\n", name, age)
	 135  
	 136  	io.WriteString(os.Stdout, s) // Ignoring error for simplicity.
	 137  
	 138  	// Output:
	 139  	// Kim is 22 years old.
	 140  }
	 141  
	 142  func ExampleFprint() {
	 143  	const name, age = "Kim", 22
	 144  	n, err := fmt.Fprint(os.Stdout, name, " is ", age, " years old.\n")
	 145  
	 146  	// The n and err return values from Fprint are
	 147  	// those returned by the underlying io.Writer.
	 148  	if err != nil {
	 149  		fmt.Fprintf(os.Stderr, "Fprint: %v\n", err)
	 150  	}
	 151  	fmt.Print(n, " bytes written.\n")
	 152  
	 153  	// Output:
	 154  	// Kim is 22 years old.
	 155  	// 21 bytes written.
	 156  }
	 157  
	 158  func ExampleFprintln() {
	 159  	const name, age = "Kim", 22
	 160  	n, err := fmt.Fprintln(os.Stdout, name, "is", age, "years old.")
	 161  
	 162  	// The n and err return values from Fprintln are
	 163  	// those returned by the underlying io.Writer.
	 164  	if err != nil {
	 165  		fmt.Fprintf(os.Stderr, "Fprintln: %v\n", err)
	 166  	}
	 167  	fmt.Println(n, "bytes written.")
	 168  
	 169  	// Output:
	 170  	// Kim is 22 years old.
	 171  	// 21 bytes written.
	 172  }
	 173  
	 174  func ExampleFprintf() {
	 175  	const name, age = "Kim", 22
	 176  	n, err := fmt.Fprintf(os.Stdout, "%s is %d years old.\n", name, age)
	 177  
	 178  	// The n and err return values from Fprintf are
	 179  	// those returned by the underlying io.Writer.
	 180  	if err != nil {
	 181  		fmt.Fprintf(os.Stderr, "Fprintf: %v\n", err)
	 182  	}
	 183  	fmt.Printf("%d bytes written.\n", n)
	 184  
	 185  	// Output:
	 186  	// Kim is 22 years old.
	 187  	// 21 bytes written.
	 188  }
	 189  
	 190  // Print, Println, and Printf lay out their arguments differently. In this example
	 191  // we can compare their behaviors. Println always adds blanks between the items it
	 192  // prints, while Print adds blanks only between non-string arguments and Printf
	 193  // does exactly what it is told.
	 194  // Sprint, Sprintln, Sprintf, Fprint, Fprintln, and Fprintf behave the same as
	 195  // their corresponding Print, Println, and Printf functions shown here.
	 196  func Example_printers() {
	 197  	a, b := 3.0, 4.0
	 198  	h := math.Hypot(a, b)
	 199  
	 200  	// Print inserts blanks between arguments when neither is a string.
	 201  	// It does not add a newline to the output, so we add one explicitly.
	 202  	fmt.Print("The vector (", a, b, ") has length ", h, ".\n")
	 203  
	 204  	// Println always inserts spaces between its arguments,
	 205  	// so it cannot be used to produce the same output as Print in this case;
	 206  	// its output has extra spaces.
	 207  	// Also, Println always adds a newline to the output.
	 208  	fmt.Println("The vector (", a, b, ") has length", h, ".")
	 209  
	 210  	// Printf provides complete control but is more complex to use.
	 211  	// It does not add a newline to the output, so we add one explicitly
	 212  	// at the end of the format specifier string.
	 213  	fmt.Printf("The vector (%g %g) has length %g.\n", a, b, h)
	 214  
	 215  	// Output:
	 216  	// The vector (3 4) has length 5.
	 217  	// The vector ( 3 4 ) has length 5 .
	 218  	// The vector (3 4) has length 5.
	 219  }
	 220  
	 221  // These examples demonstrate the basics of printing using a format string. Printf,
	 222  // Sprintf, and Fprintf all take a format string that specifies how to format the
	 223  // subsequent arguments. For example, %d (we call that a 'verb') says to print the
	 224  // corresponding argument, which must be an integer (or something containing an
	 225  // integer, such as a slice of ints) in decimal. The verb %v ('v' for 'value')
	 226  // always formats the argument in its default form, just how Print or Println would
	 227  // show it. The special verb %T ('T' for 'Type') prints the type of the argument
	 228  // rather than its value. The examples are not exhaustive; see the package comment
	 229  // for all the details.
	 230  func Example_formats() {
	 231  	// A basic set of examples showing that %v is the default format, in this
	 232  	// case decimal for integers, which can be explicitly requested with %d;
	 233  	// the output is just what Println generates.
	 234  	integer := 23
	 235  	// Each of these prints "23" (without the quotes).
	 236  	fmt.Println(integer)
	 237  	fmt.Printf("%v\n", integer)
	 238  	fmt.Printf("%d\n", integer)
	 239  
	 240  	// The special verb %T shows the type of an item rather than its value.
	 241  	fmt.Printf("%T %T\n", integer, &integer)
	 242  	// Result: int *int
	 243  
	 244  	// Println(x) is the same as Printf("%v\n", x) so we will use only Printf
	 245  	// in the following examples. Each one demonstrates how to format values of
	 246  	// a particular type, such as integers or strings. We start each format
	 247  	// string with %v to show the default output and follow that with one or
	 248  	// more custom formats.
	 249  
	 250  	// Booleans print as "true" or "false" with %v or %t.
	 251  	truth := true
	 252  	fmt.Printf("%v %t\n", truth, truth)
	 253  	// Result: true true
	 254  
	 255  	// Integers print as decimals with %v and %d,
	 256  	// or in hex with %x, octal with %o, or binary with %b.
	 257  	answer := 42
	 258  	fmt.Printf("%v %d %x %o %b\n", answer, answer, answer, answer, answer)
	 259  	// Result: 42 42 2a 52 101010
	 260  
	 261  	// Floats have multiple formats: %v and %g print a compact representation,
	 262  	// while %f prints a decimal point and %e uses exponential notation. The
	 263  	// format %6.2f used here shows how to set the width and precision to
	 264  	// control the appearance of a floating-point value. In this instance, 6 is
	 265  	// the total width of the printed text for the value (note the extra spaces
	 266  	// in the output) and 2 is the number of decimal places to show.
	 267  	pi := math.Pi
	 268  	fmt.Printf("%v %g %.2f (%6.2f) %e\n", pi, pi, pi, pi, pi)
	 269  	// Result: 3.141592653589793 3.141592653589793 3.14 (	3.14) 3.141593e+00
	 270  
	 271  	// Complex numbers format as parenthesized pairs of floats, with an 'i'
	 272  	// after the imaginary part.
	 273  	point := 110.7 + 22.5i
	 274  	fmt.Printf("%v %g %.2f %.2e\n", point, point, point, point)
	 275  	// Result: (110.7+22.5i) (110.7+22.5i) (110.70+22.50i) (1.11e+02+2.25e+01i)
	 276  
	 277  	// Runes are integers but when printed with %c show the character with that
	 278  	// Unicode value. The %q verb shows them as quoted characters, %U as a
	 279  	// hex Unicode code point, and %#U as both a code point and a quoted
	 280  	// printable form if the rune is printable.
	 281  	smile := '😀'
	 282  	fmt.Printf("%v %d %c %q %U %#U\n", smile, smile, smile, smile, smile, smile)
	 283  	// Result: 128512 128512 😀 '😀' U+1F600 U+1F600 '😀'
	 284  
	 285  	// Strings are formatted with %v and %s as-is, with %q as quoted strings,
	 286  	// and %#q as backquoted strings.
	 287  	placeholders := `foo "bar"`
	 288  	fmt.Printf("%v %s %q %#q\n", placeholders, placeholders, placeholders, placeholders)
	 289  	// Result: foo "bar" foo "bar" "foo \"bar\"" `foo "bar"`
	 290  
	 291  	// Maps formatted with %v show keys and values in their default formats.
	 292  	// The %#v form (the # is called a "flag" in this context) shows the map in
	 293  	// the Go source format. Maps are printed in a consistent order, sorted
	 294  	// by the values of the keys.
	 295  	isLegume := map[string]bool{
	 296  		"peanut":		true,
	 297  		"dachshund": false,
	 298  	}
	 299  	fmt.Printf("%v %#v\n", isLegume, isLegume)
	 300  	// Result: map[dachshund:false peanut:true] map[string]bool{"dachshund":false, "peanut":true}
	 301  
	 302  	// Structs formatted with %v show field values in their default formats.
	 303  	// The %+v form shows the fields by name, while %#v formats the struct in
	 304  	// Go source format.
	 305  	person := struct {
	 306  		Name string
	 307  		Age	int
	 308  	}{"Kim", 22}
	 309  	fmt.Printf("%v %+v %#v\n", person, person, person)
	 310  	// Result: {Kim 22} {Name:Kim Age:22} struct { Name string; Age int }{Name:"Kim", Age:22}
	 311  
	 312  	// The default format for a pointer shows the underlying value preceded by
	 313  	// an ampersand. The %p verb prints the pointer value in hex. We use a
	 314  	// typed nil for the argument to %p here because the value of any non-nil
	 315  	// pointer would change from run to run; run the commented-out Printf
	 316  	// call yourself to see.
	 317  	pointer := &person
	 318  	fmt.Printf("%v %p\n", pointer, (*int)(nil))
	 319  	// Result: &{Kim 22} 0x0
	 320  	// fmt.Printf("%v %p\n", pointer, pointer)
	 321  	// Result: &{Kim 22} 0x010203 // See comment above.
	 322  
	 323  	// Arrays and slices are formatted by applying the format to each element.
	 324  	greats := [5]string{"Kitano", "Kobayashi", "Kurosawa", "Miyazaki", "Ozu"}
	 325  	fmt.Printf("%v %q\n", greats, greats)
	 326  	// Result: [Kitano Kobayashi Kurosawa Miyazaki Ozu] ["Kitano" "Kobayashi" "Kurosawa" "Miyazaki" "Ozu"]
	 327  
	 328  	kGreats := greats[:3]
	 329  	fmt.Printf("%v %q %#v\n", kGreats, kGreats, kGreats)
	 330  	// Result: [Kitano Kobayashi Kurosawa] ["Kitano" "Kobayashi" "Kurosawa"] []string{"Kitano", "Kobayashi", "Kurosawa"}
	 331  
	 332  	// Byte slices are special. Integer verbs like %d print the elements in
	 333  	// that format. The %s and %q forms treat the slice like a string. The %x
	 334  	// verb has a special form with the space flag that puts a space between
	 335  	// the bytes.
	 336  	cmd := []byte("a⌘")
	 337  	fmt.Printf("%v %d %s %q %x % x\n", cmd, cmd, cmd, cmd, cmd, cmd)
	 338  	// Result: [97 226 140 152] [97 226 140 152] a⌘ "a⌘" 61e28c98 61 e2 8c 98
	 339  
	 340  	// Types that implement Stringer are printed the same as strings. Because
	 341  	// Stringers return a string, we can print them using a string-specific
	 342  	// verb such as %q.
	 343  	now := time.Unix(123456789, 0).UTC() // time.Time implements fmt.Stringer.
	 344  	fmt.Printf("%v %q\n", now, now)
	 345  	// Result: 1973-11-29 21:33:09 +0000 UTC "1973-11-29 21:33:09 +0000 UTC"
	 346  
	 347  	// Output:
	 348  	// 23
	 349  	// 23
	 350  	// 23
	 351  	// int *int
	 352  	// true true
	 353  	// 42 42 2a 52 101010
	 354  	// 3.141592653589793 3.141592653589793 3.14 (	3.14) 3.141593e+00
	 355  	// (110.7+22.5i) (110.7+22.5i) (110.70+22.50i) (1.11e+02+2.25e+01i)
	 356  	// 128512 128512 😀 '😀' U+1F600 U+1F600 '😀'
	 357  	// foo "bar" foo "bar" "foo \"bar\"" `foo "bar"`
	 358  	// map[dachshund:false peanut:true] map[string]bool{"dachshund":false, "peanut":true}
	 359  	// {Kim 22} {Name:Kim Age:22} struct { Name string; Age int }{Name:"Kim", Age:22}
	 360  	// &{Kim 22} 0x0
	 361  	// [Kitano Kobayashi Kurosawa Miyazaki Ozu] ["Kitano" "Kobayashi" "Kurosawa" "Miyazaki" "Ozu"]
	 362  	// [Kitano Kobayashi Kurosawa] ["Kitano" "Kobayashi" "Kurosawa"] []string{"Kitano", "Kobayashi", "Kurosawa"}
	 363  	// [97 226 140 152] [97 226 140 152] a⌘ "a⌘" 61e28c98 61 e2 8c 98
	 364  	// 1973-11-29 21:33:09 +0000 UTC "1973-11-29 21:33:09 +0000 UTC"
	 365  }
	 366  

View as plain text