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