The Go Programming Language

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

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.