src/pkg/fmt/doc.go - The Go Programming Language

Golang

Source file src/pkg/fmt/doc.go

     1	// Copyright 2009 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	/*
     6		Package fmt implements formatted I/O with functions analogous
     7		to C's printf and scanf.  The format 'verbs' are derived from C's but
     8		are simpler.
     9	
    10	
    11		Printing
    12	
    13		The verbs:
    14	
    15		General:
    16			%v	the value in a default format.
    17				when printing structs, the plus flag (%+v) adds field names
    18			%#v	a Go-syntax representation of the value
    19			%T	a Go-syntax representation of the type of the value
    20			%%	a literal percent sign; consumes no value
    21	
    22		Boolean:
    23			%t	the word true or false
    24		Integer:
    25			%b	base 2
    26			%c	the character represented by the corresponding Unicode code point
    27			%d	base 10
    28			%o	base 8
    29			%q	a single-quoted character literal safely escaped with Go syntax.
    30			%x	base 16, with lower-case letters for a-f
    31			%X	base 16, with upper-case letters for A-F
    32			%U	Unicode format: U+1234; same as "U+%04X"
    33		Floating-point and complex constituents:
    34			%b	decimalless scientific notation with exponent a power of two, 
    35				in the manner of strconv.FormatFloat with the 'b' format, 
    36				e.g. -123456p-78
    37			%e	scientific notation, e.g. -1234.456e+78
    38			%E	scientific notation, e.g. -1234.456E+78
    39			%f	decimal point but no exponent, e.g. 123.456
    40			%g	whichever of %e or %f produces more compact output
    41			%G	whichever of %E or %f produces more compact output
    42		String and slice of bytes:
    43			%s	the uninterpreted bytes of the string or slice
    44			%q	a double-quoted string safely escaped with Go syntax
    45			%x	base 16, lower-case, two characters per byte
    46			%X	base 16, upper-case, two characters per byte
    47		Pointer:
    48			%p	base 16 notation, with leading 0x
    49	
    50		There is no 'u' flag.  Integers are printed unsigned if they have unsigned type.
    51		Similarly, there is no need to specify the size of the operand (int8, int64).
    52	
    53		The width and precision control formatting and are in units of Unicode
    54		code points.  (This differs from C's printf where the units are numbers
    55		of bytes.) Either or both of the flags may be replaced with the
    56		character '*', causing their values to be obtained from the next
    57		operand, which must be of type int.
    58	
    59		For numeric values, width sets the width of the field and precision
    60		sets the number of places after the decimal, if appropriate.  For
    61		example, the format %6.2f prints 123.45.
    62	
    63		For strings, width is the minimum number of characters to output,
    64		padding with spaces if necessary, and precision is the maximum
    65		number of characters to output, truncating if necessary.
    66	
    67		Other flags:
    68			+	always print a sign for numeric values;
    69				guarantee ASCII-only output for %q (%+q)
    70			-	pad with spaces on the right rather than the left (left-justify the field)
    71			#	alternate format: add leading 0 for octal (%#o), 0x for hex (%#x);
    72				0X for hex (%#X); suppress 0x for %p (%#p);
    73				print a raw (backquoted) string if possible for %q (%#q);
    74				write e.g. U+0078 'x' if the character is printable for %U (%#U).
    75			' '	(space) leave a space for elided sign in numbers (% d);
    76				put spaces between bytes printing strings or slices in hex (% x, % X)
    77			0	pad with leading zeros rather than spaces
    78	
    79		For each Printf-like function, there is also a Print function
    80		that takes no format and is equivalent to saying %v for every
    81		operand.  Another variant Println inserts blanks between
    82		operands and appends a newline.
    83	
    84		Regardless of the verb, if an operand is an interface value,
    85		the internal concrete value is used, not the interface itself.
    86		Thus:
    87			var i interface{} = 23
    88			fmt.Printf("%v\n", i)
    89		will print 23.
    90	
    91		If an operand implements interface Formatter, that interface
    92		can be used for fine control of formatting.
    93	
    94		If the format (which is implicitly %v for Println etc.) is valid
    95		for a string (%s %q %v %x %X), the following two rules also apply:
    96	
    97		1. If an operand implements the error interface, the Error method
    98		will be used to convert the object to a string, which will then
    99		be formatted as required by the verb (if any).
   100	
   101		2. If an operand implements method String() string, that method
   102		will be used to convert the object to a string, which will then
   103		be formatted as required by the verb (if any).
   104	
   105		To avoid recursion in cases such as
   106			type X string
   107			func (x X) String() string { return Sprintf("<%s>", x) }
   108		convert the value before recurring:
   109			func (x X) String() string { return Sprintf("<%s>", string(x)) }
   110	
   111		Format errors:
   112	
   113		If an invalid argument is given for a verb, such as providing
   114		a string to %d, the generated string will contain a
   115		description of the problem, as in these examples:
   116	
   117			Wrong type or unknown verb: %!verb(type=value)
   118				Printf("%d", hi):          %!d(string=hi)
   119			Too many arguments: %!(EXTRA type=value)
   120				Printf("hi", "guys"):      hi%!(EXTRA string=guys)
   121			Too few arguments: %!verb(MISSING)
   122				Printf("hi%d"):            hi %!d(MISSING)
   123			Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
   124				Printf("%*s", 4.5, "hi"):  %!(BADWIDTH)hi
   125				Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
   126	
   127		All errors begin with the string "%!" followed sometimes
   128		by a single character (the verb) and end with a parenthesized
   129		description.
   130	
   131	
   132		Scanning
   133	
   134		An analogous set of functions scans formatted text to yield
   135		values.  Scan, Scanf and Scanln read from os.Stdin; Fscan,
   136		Fscanf and Fscanln read from a specified io.Reader; Sscan,
   137		Sscanf and Sscanln read from an argument string.  Scanln,
   138		Fscanln and Sscanln stop scanning at a newline and require that
   139		the items be followed by one; Sscanf, Fscanf and Sscanf require
   140		newlines in the input to match newlines in the format; the other
   141		routines treat newlines as spaces.
   142	
   143		Scanf, Fscanf, and Sscanf parse the arguments according to a
   144		format string, analogous to that of Printf.  For example, %x
   145		will scan an integer as a hexadecimal number, and %v will scan
   146		the default representation format for the value.
   147	
   148		The formats behave analogously to those of Printf with the
   149		following exceptions:
   150	
   151			%p is not implemented
   152			%T is not implemented
   153			%e %E %f %F %g %G are all equivalent and scan any floating point or complex value
   154			%s and %v on strings scan a space-delimited token
   155	
   156		The familiar base-setting prefixes 0 (octal) and 0x
   157		(hexadecimal) are accepted when scanning integers without a
   158		format or with the %v verb.
   159	
   160		Width is interpreted in the input text (%5s means at most
   161		five runes of input will be read to scan a string) but there
   162		is no syntax for scanning with a precision (no %5.2f, just
   163		%5f).
   164	
   165		When scanning with a format, all non-empty runs of space
   166		characters (except newline) are equivalent to a single
   167		space in both the format and the input.  With that proviso,
   168		text in the format string must match the input text; scanning
   169		stops if it does not, with the return value of the function
   170		indicating the number of arguments scanned.
   171	
   172		In all the scanning functions, if an operand implements method
   173		Scan (that is, it implements the Scanner interface) that
   174		method will be used to scan the text for that operand.  Also,
   175		if the number of arguments scanned is less than the number of
   176		arguments provided, an error is returned.
   177	
   178		All arguments to be scanned must be either pointers to basic
   179		types or implementations of the Scanner interface.
   180	
   181		Note: Fscan etc. can read one character (rune) past the input
   182		they return, which means that a loop calling a scan routine
   183		may skip some of the input.  This is usually a problem only
   184		when there is no space between input values.  If the reader
   185		provided to Fscan implements ReadRune, that method will be used
   186		to read characters.  If the reader also implements UnreadRune,
   187		that method will be used to save the character and successive
   188		calls will not lose data.  To attach ReadRune and UnreadRune
   189		methods to a reader without that capability, use
   190		bufio.NewReader.
   191	*/
   192	package fmt