一.godoc 命令介绍

  • 可以使用godoc [包] [函数名]查看包或函数的详细源码
  • 源码在学习中非常重要,经常查看源码方便理解GO的原理

    二.godoc使用

  • 查看包的源码 ``` C:\Users\zhang>godoc fmt use ‘godoc cmd/fmt’ for documentation on the fmt command

PACKAGE DOCUMENTATION

package fmt import “fmt”

  1. Package fmt implements formatted I/O with functions analogous to C's
  2. printf and scanf. The format 'verbs' are derived from C's but are
  3. simpler.
  4. Printing
  5. The verbs:
  6. General:
  7. %v the value in a default format
  8. when printing structs, the plus flag (%+v) adds field names
  9. %#v a Go-syntax representation of the value
  10. %T a Go-syntax representation of the type of the value
  11. %% a literal percent sign; consumes no value
  12. Boolean:
  13. %t the word true or false
  14. Integer:
  15. %b base 2
  16. %c the character represented by the corresponding Unicode code point
  17. %d base 10
  18. %o base 8
  19. %q a single-quoted character literal safely escaped with Go syntax.
  20. %x base 16, with lower-case letters for a-f
  21. %X base 16, with upper-case letters for A-F
  22. %U Unicode format: U+1234; same as "U+%04X"
  23. Floating-point and complex constituents:
  24. %b decimalless scientific notation with exponent a power of two,
  25. in the manner of strconv.FormatFloat with the 'b' format,
  26. e.g. -123456p-78
  27. %e scientific notation, e.g. -1.234456e+78
  28. %E scientific notation, e.g. -1.234456E+78
  29. %f decimal point but no exponent, e.g. 123.456
  30. %F synonym for %f
  31. %g %e for large exponents, %f otherwise. Precision is discussed below.
  32. %G %E for large exponents, %F otherwise
  33. String and slice of bytes (treated equivalently with these verbs):
  34. %s the uninterpreted bytes of the string or slice
  35. %q a double-quoted string safely escaped with Go syntax
  36. %x base 16, lower-case, two characters per byte
  37. %X base 16, upper-case, two characters per byte
  38. Pointer:
  39. %p base 16 notation, with leading 0x
  40. The %b, %d, %o, %x and %X verbs also work with pointers,
  41. formatting the value exactly as if it were an integer.
  42. The default format for %v is:
  43. bool: %t
  44. int, int8 etc.: %d
  45. uint, uint8 etc.: %d, %#x if printed with %#v
  46. float32, complex64, etc: %g
  47. string: %s
  48. chan: %p
  49. pointer: %p
  50. For compound objects, the elements are printed using these rules,
  51. recursively, laid out like this:
  52. struct: {field0 field1 ...}
  53. array, slice: [elem0 elem1 ...]
  54. maps: map[key1:value1 key2:value2]
  55. pointer to above: &{}, &[], &map[]
  56. Width is specified by an optional decimal number immediately preceding
  57. the verb. If absent, the width is whatever is necessary to represent the
  58. value. Precision is specified after the (optional) width by a period
  59. followed by a decimal number. If no period is present, a default
  60. precision is used. A period with no following number specifies a
  61. precision of zero. Examples:
  62. %f default width, default precision
  63. %9f width 9, default precision
  64. %.2f default width, precision 2
  65. %9.2f width 9, precision 2
  66. %9.f width 9, precision 0
  67. Width and precision are measured in units of Unicode code points, that
  68. is, runes. (This differs from C's printf where the units are always
  69. measured in bytes.) Either or both of the flags may be replaced with the
  70. character '*', causing their values to be obtained from the next operand
  71. (preceding the one to format), which must be of type int.
  72. For most values, width is the minimum number of runes to output, padding
  73. the formatted form with spaces if necessary.
  74. For strings, byte slices and byte arrays, however, precision limits the
  75. length of the input to be formatted (not the size of the output),
  76. truncating if necessary. Normally it is measured in runes, but for these
  77. types when formatted with the %x or %X format it is measured in bytes.
  78. For floating-point values, width sets the minimum width of the field and
  79. precision sets the number of places after the decimal, if appropriate,
  80. except that for %g/%G precision sets the total number of significant
  81. digits. For example, given 12.345 the format %6.3f prints 12.345 while
  82. %.3g prints 12.3. The default precision for %e, %f and %#g is 6; for %g
  83. it is the smallest number of digits necessary to identify the value
  84. uniquely.
  85. For complex numbers, the width and precision apply to the two components
  86. independently and the result is parenthesized, so %f applied to 1.2+3.4i
  87. produces (1.200000+3.400000i).
  88. Other flags:
  89. + always print a sign for numeric values;
  90. guarantee ASCII-only output for %q (%+q)
  91. - pad with spaces on the right rather than the left (left-justify the field)
  92. # alternate format: add leading 0 for octal (%#o), 0x for hex (%#x);
  93. 0X for hex (%#X); suppress 0x for %p (%#p);
  94. for %q, print a raw (backquoted) string if strconv.CanBackquote
  95. returns true;
  96. always print a decimal point for %e, %E, %f, %F, %g and %G;
  97. do not remove trailing zeros for %g and %G;
  98. write e.g. U+0078 'x' if the character is printable for %U (%#U).
  99. ' ' (space) leave a space for elided sign in numbers (% d);
  100. put spaces between bytes printing strings or slices in hex (% x, % X)
  101. 0 pad with leading zeros rather than spaces;
  102. for numbers, this moves the padding after the sign
  103. Flags are ignored by verbs that do not expect them. For example there is
  104. no alternate decimal format, so %#d and %d behave identically.
  105. For each Printf-like function, there is also a Print function that takes
  106. no format and is equivalent to saying %v for every operand. Another
  107. variant Println inserts blanks between operands and appends a newline.
  108. Regardless of the verb, if an operand is an interface value, the
  109. internal concrete value is used, not the interface itself. Thus:
  110. var i interface{} = 23
  111. fmt.Printf("%v\n", i)
  112. will print 23.
  113. Except when printed using the verbs %T and %p, special formatting
  114. considerations apply for operands that implement certain interfaces. In
  115. order of application:
  116. 1. If the operand is a reflect.Value, the operand is replaced by the
  117. concrete value that it holds, and printing continues with the next rule.
  118. 2. If an operand implements the Formatter interface, it will be invoked.
  119. Formatter provides fine control of formatting.
  120. 3. If the %v verb is used with the # flag (%#v) and the operand
  121. implements the GoStringer interface, that will be invoked.
  122. If the format (which is implicitly %v for Println etc.) is valid for a
  123. string (%s %q %v %x %X), the following two rules apply:
  124. 4. If an operand implements the error interface, the Error method will
  125. be invoked to convert the object to a string, which will then be
  126. formatted as required by the verb (if any).
  127. 5. If an operand implements method String() string, that method will be
  128. invoked to convert the object to a string, which will then be formatted
  129. as required by the verb (if any).
  130. For compound operands such as slices and structs, the format applies to
  131. the elements of each operand, recursively, not to the operand as a
  132. whole. Thus %q will quote each element of a slice of strings, and %6.2f
  133. will control formatting for each element of a floating-point array.
  134. However, when printing a byte slice with a string-like verb (%s %q %x
  135. %X), it is treated identically to a string, as a single item.
  136. To avoid recursion in cases such as
  137. type X string
  138. func (x X) String() string { return Sprintf("<%s>", x) }
  139. convert the value before recurring:
  140. func (x X) String() string { return Sprintf("<%s>", string(x)) }
  141. Infinite recursion can also be triggered by self-referential data
  142. structures, such as a slice that contains itself as an element, if that
  143. type has a String method. Such pathologies are rare, however, and the
  144. package does not protect against them.
  145. When printing a struct, fmt cannot and therefore does not invoke
  146. formatting methods such as Error or String on unexported fields.
  147. Explicit argument indexes:
  148. In Printf, Sprintf, and Fprintf, the default behavior is for each
  149. formatting verb to format successive arguments passed in the call.
  150. However, the notation [n] immediately before the verb indicates that the
  151. nth one-indexed argument is to be formatted instead. The same notation
  152. before a '*' for a width or precision selects the argument index holding
  153. the value. After processing a bracketed expression [n], subsequent verbs
  154. will use arguments n+1, n+2, etc. unless otherwise directed.
  155. For example,
  156. fmt.Sprintf("%[2]d %[1]d\n", 11, 22)
  157. will yield "22 11", while
  158. fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6)
  159. equivalent to
  160. fmt.Sprintf("%6.2f", 12.0)
  161. will yield " 12.00". Because an explicit index affects subsequent verbs,
  162. this notation can be used to print the same values multiple times by
  163. resetting the index for the first argument to be repeated:
  164. fmt.Sprintf("%d %d %#[1]x %#x", 16, 17)
  165. will yield "16 17 0x10 0x11".
  166. Format errors:
  167. If an invalid argument is given for a verb, such as providing a string
  168. to %d, the generated string will contain a description of the problem,
  169. as in these examples:
  170. Wrong type or unknown verb: %!verb(type=value)
  171. Printf("%d", hi): %!d(string=hi)
  172. Too many arguments: %!(EXTRA type=value)
  173. Printf("hi", "guys"): hi%!(EXTRA string=guys)
  174. Too few arguments: %!verb(MISSING)
  175. Printf("hi%d"): hi%!d(MISSING)
  176. Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
  177. Printf("%*s", 4.5, "hi"): %!(BADWIDTH)hi
  178. Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
  179. Invalid or invalid use of argument index: %!(BADINDEX)
  180. Printf("%*[2]d", 7): %!d(BADINDEX)
  181. Printf("%.[2]d", 7): %!d(BADINDEX)
  182. All errors begin with the string "%!" followed sometimes by a single
  183. character (the verb) and end with a parenthesized description.
  184. If an Error or String method triggers a panic when called by a print
  185. routine, the fmt package reformats the error message from the panic,
  186. decorating it with an indication that it came through the fmt package.
  187. For example, if a String method calls panic("bad"), the resulting
  188. formatted message will look like
  189. %!s(PANIC=bad)
  190. The %!s just shows the print verb in use when the failure occurred. If
  191. the panic is caused by a nil receiver to an Error or String method,
  192. however, the output is the undecorated string, "<nil>".
  193. Scanning
  194. An analogous set of functions scans formatted text to yield values.
  195. Scan, Scanf and Scanln read from os.Stdin; Fscan, Fscanf and Fscanln
  196. read from a specified io.Reader; Sscan, Sscanf and Sscanln read from an
  197. argument string.
  198. Scan, Fscan, Sscan treat newlines in the input as spaces.
  199. Scanln, Fscanln and Sscanln stop scanning at a newline and require that
  200. the items be followed by a newline or EOF.
  201. Scanf, Fscanf, and Sscanf parse the arguments according to a format
  202. string, analogous to that of Printf. In the text that follows, 'space'
  203. means any Unicode whitespace character except newline.
  204. In the format string, a verb introduced by the % character consumes and
  205. parses input; these verbs are described in more detail below. A
  206. character other than %, space, or newline in the format consumes exactly
  207. that input character, which must be present. A newline with zero or more
  208. spaces before it in the format string consumes zero or more spaces in
  209. the input followed by a single newline or the end of the input. A space
  210. following a newline in the format string consumes zero or more spaces in
  211. the input. Otherwise, any run of one or more spaces in the format string
  212. consumes as many spaces as possible in the input. Unless the run of
  213. spaces in the format string appears adjacent to a newline, the run must
  214. consume at least one space from the input or find the end of the input.
  215. The handling of spaces and newlines differs from that of C's scanf
  216. family: in C, newlines are treated as any other space, and it is never
  217. an error when a run of spaces in the format string finds no spaces to
  218. consume in the input.
  219. The verbs behave analogously to those of Printf. For example, %x will
  220. scan an integer as a hexadecimal number, and %v will scan the default
  221. representation format for the value. The Printf verbs %p and %T and the
  222. flags # and + are not implemented, and the verbs %e %E %f %F %g and %G
  223. are all equivalent and scan any floating-point or complex value.
  224. Input processed by verbs is implicitly space-delimited: the
  225. implementation of every verb except %c starts by discarding leading
  226. spaces from the remaining input, and the %s verb (and %v reading into a
  227. string) stops consuming input at the first space or newline character.
  228. The familiar base-setting prefixes 0 (octal) and 0x (hexadecimal) are
  229. accepted when scanning integers without a format or with the %v verb.
  230. Width is interpreted in the input text but there is no syntax for
  231. scanning with a precision (no %5.2f, just %5f). If width is provided, it
  232. applies after leading spaces are trimmed and specifies the maximum
  233. number of runes to read to satisfy the verb. For example,
  234. Sscanf(" 1234567 ", "%5s%d", &s, &i)
  235. will set s to "12345" and i to 67 while
  236. Sscanf(" 12 34 567 ", "%5s%d", &s, &i)
  237. will set s to "12" and i to 34.
  238. In all the scanning functions, a carriage return followed immediately by
  239. a newline is treated as a plain newline (\r\n means the same as \n).
  240. In all the scanning functions, if an operand implements method Scan
  241. (that is, it implements the Scanner interface) that method will be used
  242. to scan the text for that operand. Also, if the number of arguments
  243. scanned is less than the number of arguments provided, an error is
  244. returned.
  245. All arguments to be scanned must be either pointers to basic types or
  246. implementations of the Scanner interface.
  247. Like Scanf and Fscanf, Sscanf need not consume its entire input. There
  248. is no way to recover how much of the input string Sscanf used.
  249. Note: Fscan etc. can read one character (rune) past the input they
  250. return, which means that a loop calling a scan routine may skip some of
  251. the input. This is usually a problem only when there is no space between
  252. input values. If the reader provided to Fscan implements ReadRune, that
  253. method will be used to read characters. If the reader also implements
  254. UnreadRune, that method will be used to save the character and
  255. successive calls will not lose data. To attach ReadRune and UnreadRune
  256. methods to a reader without that capability, use bufio.NewReader.

FUNCTIONS

func Errorf(format string, a …interface{}) error Errorf formats according to a format specifier and returns the string as a value that satisfies error.

func Fprint(w io.Writer, a …interface{}) (n int, err error) Fprint formats using the default formats for its operands and writes to w. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.

func Fprintf(w io.Writer, format string, a …interface{}) (n int, err error) Fprintf formats according to a format specifier and writes to w. It returns the number of bytes written and any write error encountered.

func Fprintln(w io.Writer, a …interface{}) (n int, err error) Fprintln formats using the default formats for its operands and writes to w. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.

func Fscan(r io.Reader, a …interface{}) (n int, err error) Fscan scans text read from r, storing successive space-separated values into successive arguments. Newlines count as space. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.

func Fscanf(r io.Reader, format string, a …interface{}) (n int, err error) Fscanf scans text read from r, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully parsed. Newlines in the input must match newlines in the format.

func Fscanln(r io.Reader, a …interface{}) (n int, err error) Fscanln is similar to Fscan, but stops scanning at a newline and after the final item there must be a newline or EOF.

func Print(a …interface{}) (n int, err error) Print formats using the default formats for its operands and writes to standard output. Spaces are added between operands when neither is a string. It returns the number of bytes written and any write error encountered.

func Printf(format string, a …interface{}) (n int, err error) Printf formats according to a format specifier and writes to standard output. It returns the number of bytes written and any write error encountered.

func Println(a …interface{}) (n int, err error) Println formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.

func Scan(a …interface{}) (n int, err error) Scan scans text read from standard input, storing successive space-separated values into successive arguments. Newlines count as space. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.

func Scanf(format string, a …interface{}) (n int, err error) Scanf scans text read from standard input, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why. Newlines in the input must match newlines in the format. The one exception: the verb %c always scans the next rune in the input, even if it is a space (or tab etc.) or newline.

func Scanln(a …interface{}) (n int, err error) Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF.

func Sprint(a …interface{}) string Sprint formats using the default formats for its operands and returns the resulting string. Spaces are added between operands when neither is a string.

func Sprintf(format string, a …interface{}) string Sprintf formats according to a format specifier and returns the resulting string.

func Sprintln(a …interface{}) string Sprintln formats using the default formats for its operands and returns the resulting string. Spaces are always added between operands and a newline is appended.

func Sscan(str string, a …interface{}) (n int, err error) Sscan scans the argument string, storing successive space-separated values into successive arguments. Newlines count as space. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.

func Sscanf(str string, format string, a …interface{}) (n int, err error) Sscanf scans the argument string, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully parsed. Newlines in the input must match newlines in the format.

func Sscanln(str string, a …interface{}) (n int, err error) Sscanln is similar to Sscan, but stops scanning at a newline and after the final item there must be a newline or EOF.

TYPES

type Formatter interface { Format(f State, c rune) } Formatter is the interface implemented by values with a custom formatter. The implementation of Format may call Sprint(f) or Fprint(f) etc. to generate its output.

type GoStringer interface { GoString() string } GoStringer is implemented by any value that has a GoString method, which defines the Go syntax for that value. The GoString method is used to print values passed as an operand to a %#v format.

type ScanState interface { // ReadRune reads the next rune (Unicode code point) from the input. // If invoked during Scanln, Fscanln, or Sscanln, ReadRune() will // return EOF after returning the first ‘\n’ or when reading beyond // the specified width. ReadRune() (r rune, size int, err error) // UnreadRune causes the next call to ReadRune to return the same rune. UnreadRune() error // SkipSpace skips space in the input. Newlines are treated appropriately // for the operation being performed; see the package documentation // for more information. SkipSpace() // Token skips space in the input if skipSpace is true, then returns the // run of Unicode code points c satisfying f(c). If f is nil, // !unicode.IsSpace(c) is used; that is, the token will hold non-space // characters. Newlines are treated appropriately for the operation being // performed; see the package documentation for more information. // The returned slice points to shared data that may be overwritten // by the next call to Token, a call to a Scan function using the ScanState // as input, or when the calling Scan method returns. Token(skipSpace bool, f func(rune) bool) (token []byte, err error) // Width returns the value of the width option and whether it has been set. // The unit is Unicode code points. Width() (wid int, ok bool) // Because ReadRune is implemented by the interface, Read should never be // called by the scanning routines and a valid implementation of // ScanState may choose always to return an error from Read. Read(buf []byte) (n int, err error) } ScanState represents the scanner state passed to custom scanners. Scanners may do rune-at-a-time scanning or ask the ScanState to discover the next space-delimited token.

type Scanner interface { Scan(state ScanState, verb rune) error } Scanner is implemented by any value that has a Scan method, which scans the input for the representation of a value and stores the result in the receiver, which must be a pointer to be useful. The Scan method is called for any argument to Scan, Scanf, or Scanln that implements it.

type State interface { // Write is the function to call to emit formatted output to be printed. Write(b []byte) (n int, err error) // Width returns the value of the width option and whether it has been set. Width() (wid int, ok bool) // Precision returns the value of the precision option and whether it has been set. Precision() (prec int, ok bool)

  1. // Flag reports whether the flag c, a character, has been set.
  2. Flag(c int) bool

} State represents the printer state passed to custom formatters. It provides access to the io.Writer interface plus information about the flags and options for the operand’s format specifier.

type Stringer interface { String() string } Stringer is implemented by any value that has a String method, which defines the ``native’’ format for that value. The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print.

  1. - 查看某个包中某个函数

C:\Users\zhang>godoc fmt Println use ‘godoc cmd/fmt’ for documentation on the fmt command

func Println(a …interface{}) (n int, err error) Println formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered. ```