fmt 包的含义是什么?

开始学习go语言,就是fmt的包,这个包为啥叫fmt包呢?可以参考 go语言的文档。

参考:fmt/doc.go (下面代码所示)

go语言的fmt package ,实现了同C语言的printf,scanf类似 formatted I/O 的functions。

这个fomat 动词衍生于C语言,但是相比较更加简单。

go doc fmt

Package fmt implements formatted I/O with functions analogous
    to C's printf and scanf.  The format 'verbs' are derived from C's but
    are simpler.

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file./*Package fmt implements formatted I/O with functions analogousto C's printf and scanf.  The format 'verbs' are derived from C's butare simpler.PrintingThe verbs:General:%v   the value in a default formatwhen printing structs, the plus flag (%+v) adds field names%#v    a Go-syntax representation of the value%T   a Go-syntax representation of the type of the value%%   a literal percent sign; consumes no valueBoolean:%t the word true or falseInteger:%b    base 2%c    the character represented by the corresponding Unicode code point%d base 10%o   base 8%O    base 8 with 0o prefix%q a single-quoted character literal safely escaped with Go syntax.%x  base 16, with lower-case letters for a-f%X  base 16, with upper-case letters for A-F%U  Unicode format: U+1234; same as "U+%04X"Floating-point and complex constituents:%b  decimalless scientific notation with exponent a power of two,in the manner of strconv.FormatFloat with the 'b' format,e.g. -123456p-78%e  scientific notation, e.g. -1.234456e+78%E  scientific notation, e.g. -1.234456E+78%f  decimal point but no exponent, e.g. 123.456%F   synonym for %f%g    %e for large exponents, %f otherwise. Precision is discussed below.%G   %E for large exponents, %F otherwise%x  hexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20%X   upper-case hexadecimal notation, e.g. -0X1.23ABCP+20String and slice of bytes (treated equivalently with these verbs):%s   the uninterpreted bytes of the string or slice%q    a double-quoted string safely escaped with Go syntax%x  base 16, lower-case, two characters per byte%X  base 16, upper-case, two characters per byteSlice:%p    address of 0th element in base 16 notation, with leading 0xPointer:%p   base 16 notation, with leading 0xThe %b, %d, %o, %x and %X verbs also work with pointers,formatting the value exactly as if it were an integer.The default format for %v is:bool:                    %tint, int8 etc.:          %duint, uint8 etc.:        %d, %#x if printed with %#vfloat32, complex64, etc: %gstring:                  %schan:                    %ppointer:                 %pFor compound objects, the elements are printed using these rules, recursively,laid out like this:struct:             {field0 field1 ...}array, slice:       [elem0 elem1 ...]maps:               map[key1:value1 key2:value2 ...]pointer to above:   &{}, &[], &map[]Width is specified by an optional decimal number immediately preceding the verb.If absent, the width is whatever is necessary to represent the value.Precision is specified after the (optional) width by a period followed by adecimal number. If no period is present, a default precision is used.A period with no following number specifies a precision of zero.Examples:%f     default width, default precision%9f    width 9, default precision%.2f   default width, precision 2%9.2f  width 9, precision 2%9.f   width 9, precision 0Width and precision are measured in units of Unicode code points,that is, runes. (This differs from C's printf where theunits are always measured in bytes.) Either or both of the flagsmay be replaced with the character '*', causing their values to beobtained from the next operand (preceding the one to format),which must be of type int.For most values, width is the minimum number of runes to output,padding the formatted form with spaces if necessary.For strings, byte slices and byte arrays, however, precisionlimits the length of the input to be formatted (not the size ofthe output), truncating if necessary. Normally it is measured inrunes, but for these types when formatted with the %x or %X formatit is measured in bytes.For floating-point values, width sets the minimum width of the field andprecision sets the number of places after the decimal, if appropriate,except that for %g/%G precision sets the maximum number of significantdigits (trailing zeros are removed). For example, given 12.345 the format%6.3f prints 12.345 while %.3g prints 12.3. The default precision for %e, %fand %#g is 6; for %g it is the smallest number of digits necessary to identifythe value uniquely.For complex numbers, the width and precision apply to the twocomponents independently and the result is parenthesized, so %f appliedto 1.2+3.4i produces (1.200000+3.400000i).Other flags:+   always print a sign for numeric values;guarantee ASCII-only output for %q (%+q)-   pad with spaces on the right rather than the left (left-justify the field)# alternate format: add leading 0b for binary (%#b), 0 for octal (%#o),0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p);for %q, print a raw (backquoted) string if strconv.CanBackquotereturns true;always print a decimal point for %e, %E, %f, %F, %g and %G;do not remove trailing zeros for %g and %G;write e.g. U+0078 'x' if the character is printable for %U (%#U).' '    (space) leave a space for elided sign in numbers (% d);put spaces between bytes printing strings or slices in hex (% x, % X)0   pad with leading zeros rather than spaces;for numbers, this moves the padding after the signFlags are ignored by verbs that do not expect them.For example there is no alternate decimal format, so %#d and %dbehave identically.For each Printf-like function, there is also a Print functionthat takes no format and is equivalent to saying %v for everyoperand.  Another variant Println inserts blanks betweenoperands and appends a newline.Regardless of the verb, if an operand is an interface value,the internal concrete value is used, not the interface itself.Thus:var i interface{} = 23fmt.Printf("%v\n", i)will print 23.Except when printed using the verbs %T and %p, specialformatting considerations apply for operands that implementcertain interfaces. In order of application:1. If the operand is a reflect.Value, the operand is replaced by theconcrete value that it holds, and printing continues with the next rule.2. If an operand implements the Formatter interface, it willbe invoked. In this case the interpretation of verbs and flags iscontrolled by that implementation.3. If the %v verb is used with the # flag (%#v) and the operandimplements the GoStringer interface, that will be invoked.If the format (which is implicitly %v for Println etc.) is validfor a string (%s %q %v %x %X), the following two rules apply:4. If an operand implements the error interface, the Error methodwill be invoked to convert the object to a string, which will thenbe formatted as required by the verb (if any).5. If an operand implements method String() string, that methodwill be invoked to convert the object to a string, which will thenbe formatted as required by the verb (if any).For compound operands such as slices and structs, the formatapplies to the elements of each operand, recursively, not to theoperand as a whole. Thus %q will quote each element of a sliceof strings, and %6.2f will control formatting for each elementof a floating-point array.However, when printing a byte slice with a string-like verb(%s %q %x %X), it is treated identically to a string, as a single item.To avoid recursion in cases such astype X stringfunc (x X) String() string { return Sprintf("<%s>", x) }convert the value before recurring:func (x X) String() string { return Sprintf("<%s>", string(x)) }Infinite recursion can also be triggered by self-referential datastructures, such as a slice that contains itself as an element, ifthat type has a String method. Such pathologies are rare, however,and the package does not protect against them.When printing a struct, fmt cannot and therefore does not invokeformatting methods such as Error or String on unexported fields.Explicit argument indexesIn Printf, Sprintf, and Fprintf, the default behavior is for eachformatting verb to format successive arguments passed in the call.However, the notation [n] immediately before the verb indicates that thenth one-indexed argument is to be formatted instead. The same notationbefore a '*' for a width or precision selects the argument index holdingthe value. After processing a bracketed expression [n], subsequent verbswill use arguments n+1, n+2, etc. unless otherwise directed.For example,fmt.Sprintf("%[2]d %[1]d\n", 11, 22)will yield "22 11", whilefmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6)equivalent tofmt.Sprintf("%6.2f", 12.0)will yield " 12.00". Because an explicit index affects subsequent verbs,this notation can be used to print the same values multiple timesby resetting the index for the first argument to be repeated:fmt.Sprintf("%d %d %#[1]x %#x", 16, 17)will yield "16 17 0x10 0x11".Format errorsIf an invalid argument is given for a verb, such as providinga string to %d, the generated string will contain adescription of the problem, as in these examples:Wrong type or unknown verb: %!verb(type=value)Printf("%d", "hi"):        %!d(string=hi)Too many arguments: %!(EXTRA type=value)Printf("hi", "guys"):      hi%!(EXTRA string=guys)Too few arguments: %!verb(MISSING)Printf("hi%d"):            hi%!d(MISSING)Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)Printf("%*s", 4.5, "hi"):  %!(BADWIDTH)hiPrintf("%.*s", 4.5, "hi"): %!(BADPREC)hiInvalid or invalid use of argument index: %!(BADINDEX)Printf("%*[2]d", 7):       %!d(BADINDEX)Printf("%.[2]d", 7):       %!d(BADINDEX)All errors begin with the string "%!" followed sometimesby a single character (the verb) and end with a parenthesizeddescription.If an Error or String method triggers a panic when called by aprint routine, the fmt package reformats the error messagefrom the panic, decorating it with an indication that it camethrough the fmt package.  For example, if a String methodcalls panic("bad"), the resulting formatted message will looklike%!s(PANIC=bad)The %!s just shows the print verb in use when the failureoccurred. If the panic is caused by a nil receiver to an Erroror String method, however, the output is the undecoratedstring, "<nil>".ScanningAn analogous set of functions scans formatted text to yieldvalues.  Scan, Scanf and Scanln read from os.Stdin; Fscan,Fscanf and Fscanln read from a specified io.Reader; Sscan,Sscanf and Sscanln read from an argument string.Scan, Fscan, Sscan treat newlines in the input as spaces.Scanln, Fscanln and Sscanln stop scanning at a newline andrequire that the items be followed by a newline or EOF.Scanf, Fscanf, and Sscanf parse the arguments according to aformat string, analogous to that of Printf. In the text thatfollows, 'space' means any Unicode whitespace characterexcept newline.In the format string, a verb introduced by the % characterconsumes and parses input; these verbs are described in moredetail below. A character other than %, space, or newline inthe format consumes exactly that input character, which mustbe present. A newline with zero or more spaces before it inthe format string consumes zero or more spaces in the inputfollowed by a single newline or the end of the input. A spacefollowing a newline in the format string consumes zero or morespaces in the input. Otherwise, any run of one or more spacesin the format string consumes as many spaces as possible inthe input. Unless the run of spaces in the format stringappears adjacent to a newline, the run must consume at leastone space from the input or find the end of the input.The handling of spaces and newlines differs from that of C'sscanf family: in C, newlines are treated as any other space,and it is never an error when a run of spaces in the formatstring finds no spaces to consume in the input.The verbs behave analogously to those of Printf.For example, %x will scan an integer as a hexadecimal number,and %v will scan the default representation format for the value.The Printf verbs %p and %T and the flags # and + are not implemented.For floating-point and complex values, all valid formatting verbs(%b %e %E %f %F %g %G %x %X and %v) are equivalent and acceptboth decimal and hexadecimal notation (for example: "2.3e+7", "0x4.5p-8")and digit-separating underscores (for example: "3.14159_26535_89793").Input processed by verbs is implicitly space-delimited: theimplementation of every verb except %c starts by discardingleading spaces from the remaining input, and the %s verb(and %v reading into a string) stops consuming input at the firstspace or newline character.The familiar base-setting prefixes 0b (binary), 0o and 0 (octal),and 0x (hexadecimal) are accepted when scanning integerswithout a format or with the %v verb, as are digit-separatingunderscores.Width is interpreted in the input text but there is nosyntax for scanning with a precision (no %5.2f, just %5f).If width is provided, it applies after leading spaces aretrimmed and specifies the maximum number of runes to readto satisfy the verb. For example,Sscanf(" 1234567 ", "%5s%d", &s, &i)will set s to "12345" and i to 67 whileSscanf(" 12 34 567 ", "%5s%d", &s, &i)will set s to "12" and i to 34.In all the scanning functions, a carriage return followedimmediately by a newline is treated as a plain newline(\r\n means the same as \n).In all the scanning functions, if an operand implements methodScan (that is, it implements the Scanner interface) thatmethod will be used to scan the text for that operand.  Also,if the number of arguments scanned is less than the number ofarguments provided, an error is returned.All arguments to be scanned must be either pointers to basictypes or implementations of the Scanner interface.Like Scanf and Fscanf, Sscanf need not consume its entire input.There is no way to recover how much of the input string Sscanf used.Note: Fscan etc. can read one character (rune) past the inputthey return, which means that a loop calling a scan routinemay skip some of the input.  This is usually a problem onlywhen there is no space between input values.  If the readerprovided to Fscan implements ReadRune, that method will be usedto read characters.  If the reader also implements UnreadRune,that method will be used to save the character and successivecalls will not lose data.  To attach ReadRune and UnreadRunemethods to a reader without that capability, usebufio.NewReader.
*/
package fmt

Go语言学习 fmt包-是什么意思相关推荐

  1. 【golang】Go语言学习-time包

    go语言的time包 组成 time.Duration(时长,耗时) time.Time(时间点) time.C(放时间点的管道)[ Time.C:=make(chan time.Time) ] ti ...

  2. go语言复数包_go语言学习之包和变量详解

    前言 本文主要介绍了关于go语言之包和变量的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 一.包的概念 包是go语言中不可缺少部分,在每个go源码的第一行进行定义,定义方 ...

  3. R语言︱H2o深度学习的一些R语言实践——H2o包

    每每以为攀得众山小,可.每每又切实来到起点,大牛们,缓缓脚步来俺笔记葩分享一下吧,please~ --------------------------- R语言H2o包的几个应用案例 笔者寄语:受启发 ...

  4. R语言使用mgcv包中的gam函数拟合广义加性模型(Generalized Additive Model,GAMs):从广义加性模型GAM中抽取学习到的样条函数(spline function)

    R语言使用mgcv包中的gam函数拟合广义加性模型(Generalized Additive Model,GAMs):从广义加性模型GAM中抽取学习到的样条函数(spline function) 目录

  5. python是最好的语言表情包_Python语言学习之如何通过Python用表情包自动回复微信拍一拍...

    本篇文章主要介绍了Python语言学习之如何通过Python用表情包自动回复微信拍一拍,通过具体的内容展现,希望对Python语言的学习有所帮助. 前段时间微信上线了拍一拍功能,刚推出就被有才的网友玩 ...

  6. go笔记(3)Go语言fmt包的用法

    介绍 fmt是一个用于输入输出常用的库 在fmt包,有关格式化输入输出的方法就有两大类:scan和print 分别在scan.go和print.go文件中 print:输出函数 print 系列主要用 ...

  7. 6.方法(go语言学习笔记)

    6.方法(go语言学习笔记) 目录 定义 匿名字段 方法集 表达式 1. 定义 方法是与对象实例绑定的特殊函数. 方法是面向对象编程的基本概念,用于维护和展示对象的自身状态.对象是内敛的,每个实例对象 ...

  8. Go 语言学习笔记(一):基础知识

    目录 语言简介 初识 Go 程序 Go 词法单元 变量和常量 复合数据类型 语言简介 已经有那么多种编程语言了,为什么还要发明新语言?为什么还要去学习新语言?相信不少人都有这样的疑问.答案很简单,虽然 ...

  9. 我的Go语言学习之旅二:入门初体验 Hello World

    好吧,所有的程序员们都已经习惯了,学习任何一门语言,我们都会以Hello World实例开始我们的学习,我也不例外.先来一个简单的例子 打开编辑器 (可以用记事本,我已经习惯 Notepad++了)输 ...

最新文章

  1. 排序(一)归并、快排、优先队列等(图文具体解释)
  2. Linux软件安装包中devel与非devel包之间的区别
  3. JAVA中深拷贝与浅拷贝(在网上找到的) 希望对于理解深拷贝与浅拷贝有帮助...
  4. 使用 C# 代码实现拓扑排序
  5. java 并发 线程安全_Java并发教程–线程安全设计
  6. ASP.NE浏览时 无法显示 XML 页
  7. 【蓝桥杯】题目 1117: K-进制数
  8. Android handleMessage和sendMessage 简单示例
  9. Linux下部署WordPress
  10. 【已解决】map container is already initialized——页面切换瓦片图不出来的问题
  11. Spring Cloud 菜鸟教程 1 简介
  12. 计算机的算数逻辑单元控制单元统称为,算术控制单元
  13. Linux搭建Elasticsearch集群
  14. 什么叫状态服务器 博客,pending是什么意思?HTTP Status pending (进程信号的未决状态)详解...
  15. 安卓RecyclerView万能分割线
  16. ADC和DAC的DNL和INL
  17. 关于 SONY WF1000XM3 在 Windows 10 下蓝牙连接只有 Handfree 没有 Stereo 模式
  18. 【SCIR笔记】文档级事件抽取简述
  19. P10-Windows与网络基础-Windows基本命令-DOS网络相关操作命令
  20. 四阶段法-出行分布计算 底特律法

热门文章

  1. pm2自身成为性能瓶颈
  2. java中stopwatch,Java StopWatch.stop方法代碼示例
  3. nginx之rewrite规则未加引号导致检查nginx语法报错
  4. 将linux终端的输出信息保存到log中
  5. android改微信号码,微信已支持改微信号:仅限安卓最新版,附修改办法
  6. java开发防伪码_企业编码生成系统智能批量生成带数据分析功能的防伪码
  7. columnmodel 动态cell编辑
  8. 《编程机制探析》第六章 面向对象
  9. 如何解决网络成瘾对青少年的危害
  10. nVIDIA Jetson TX1 内核kernel编译