0°

Go语言基础语法

Go语言基础语法

一.go语言介绍

1.Go语言简介

  • Go 语言(或 Golang)起源于 2007 年,并在 2009 年正式对外发布。Go 是非常年轻的一门语言,它的主要目标是“兼具 Python 等动态语言的开发速度和 C/C++等编译型语言的性能与安全性”
  • Go 语言是编程语言设计的又一次尝试,是对类C语言的重大改进,它不但能让你访问底层操作系统,还提供了强大的网络编程和并发编程支持。Go 语言的用途众多,可以进行网络编程、系统编程、并发编程、分布式编程。
  • Go 语言的推出,旨在不损失应用程序性能的情况下降低代码的复杂性,具有“部署简单、并发性好、语言设计良好、执行性能好”等优势,目前国内诸多 IT 公司均已采用 Go 语言开发项目。
  • Go 语言有时候被描述为“C 类似语言”,或者是“21 世纪的 C 语言”。Go 从 C 语言继承了相似的表达式语法、控制流结构、基础数据类型、调用参数传值、指针等很多思想,还有 C 语言一直所看中的编译后机器码的运行效率以及和现有操作系统的无缝适配。
  • 因为 Go 语言没有类和继承的概念,所以它和 Java 或 C++ 看起来并不相同。但是它通过接口(interface)的概念来实现多态性。Go 语言有一个清晰易懂的轻量级类型系统,在类型之间也没有层级之说。因此可以说 Go 语言是一门混合型的语言。
  • 此外,很多重要的开源项目都是使用 Go 语言开发的,其中包括 Docker、Go-Ethereum、Thrraform 和 Kubernetes。

2.Go语言创始人

对语言进行评估时,明白设计者的动机以及语言要解决的问题很重要。Go 语言出自 Ken Thompson 和 Rob Pike、Robert Griesemer 之手,他们都是计算机科学领域的重量级人物。
贝尔实验室 Unix 团队成员,C 语言、Unix 和 Plan 9 的创始人之一,在 20 世纪 70 年代,设计并实现了最初的 UNIX 操作系统,仅从这一点说,他对计算机科学的贡献怎么强调都不过分。他还与 Rob Pike 合作设计了 UTF-8 编码方案。

2) Rob Pike

Go 语言项目总负责人,贝尔实验室 Unix 团队成员,除帮助设计 UTF-8 外,还帮助开发了分布式多用户操作系统 Plan 9,,Inferno 操作系统和 Limbo 编程语言,并与人合著了《The Unix Programming Environment》,对 UNIX 的设计理念做了正统的阐述。
就职于 Google,参与开发 Java HotSpot 虚拟机,对语言设计有深入的认识,并负责 Chrome 浏览器和 Node.js 使用的 Google V8 JavaScript 引擎的代码生成部分。

Go 语言的所有设计者都说,设计 Go 语言是因为 C++ 给他们带来了挫败感。在 Google I/O 2012 的 Go 设计小组见面会上,Rob Pike 是这样说的:


1
2
3
1我们做了大量的 C++ 开发,厌烦了等待编译完成,尽管这是玩笑,但在很大程度上来说也是事实。
2
3

3.Go语言优势

  • 语法简单


1
2
3
4
5
1   var a,b=1,2
2   a,b=b,a
3   fmt.Println(a,b)
4
5
  • 可以直接编译成机器码

  • 静态数据类型和编译语言


1
2
3
4
1   a:=1
2   b:=false
3
4
  • 内置支持并发


1
2
3
4
5
1   go func() {
2       //do something
3   }()
4
5
  • 内置垃圾回收
  • 部署简单
  • 强大的标准库

4.Go是编译型语言

Go 使用编译器来编译代码。编译器将源代码编译成二进制(或字节码)格式;在编译代码时,编译器检查错误、优化性能并输出可在不同平台上运行的二进制文件。要创建并运行 Go 程序,程序员必须执行如下步骤。

使用文本编辑器创建 Go 程序;

保存文件;

编译程序;

运行编译得到的可执行文件。

这不同于 Python、Ruby 和 JavaScript 等语言,它们不包含编译步骤。Go 自带了编译器,因此无须单独安装编译器。

5.为什么要学习Go语言

如果你要创建系统程序,或者基于网络的程序,Go 语言是很不错的选择。作为一种相对较新的语言,它是由经验丰富且受人尊敬的计算机科学家设计的,旨在应对创建大型并发网络程序面临的挑战。

在 Go 语言出现之前,开发者们总是面临非常艰难的抉择,究竟是使用执行速度快但是编译速度并不理想的语言(如:C++),还是使用编译速度较快但执行效率不佳的语言(如:.NET、Java),或者说开发难度较低但执行速度一般的动态语言呢?显然,Go 语言在这 3 个条件之间做到了最佳的平衡:快速编译,高效执行,易于开发。

Go 语言支持交叉编译,比如说你可以在运行 Linux 系统的计算机上开发可以在 Windows 上运行的应用程序。这是第一门完全支持 UTF-8 的编程语言,这不仅体现在它可以处理使用 UTF-8 编码的字符串,就连它的源码文件格式都是使用的 UTF-8 编码。Go 语言做到了真正的国际化!

6.Go语言适用场景

  • 服务器编程.实现日志处理,虚拟机处理,文件处理等
  • 分布式系统或数据库代理
  • 网络编程,包含web应用
  • 云平台

7.市场占有率

  • 根据Tiobe中Go语言的排行在逐年上升.

在这里插入图片描述

8.Go语言吉祥物

二.环境变量配置

1.下载地址

  • 由于Google退出中国,所以国内无法直接访问到Go语言的官网
  • 但是可以通过Go语言中文网进行加载资源和交流Go语言技术

https://studygolang.com/

2.下载步骤

  • 直接进入到Go语言中文网下载页面

在这里插入图片描述

  • 选择要下载的版本

  • 首先要确定版本号,本套视频使用的Go1.10.1

    • 然后确定自己的操作系统,windows或linux等,本阶段使用Window操作系统进行讲解
    • 如果是windows确定自己系统位数,32位系统选择386,64位系统选择amd64
    • 扩展名.msi表示安装版.zip为解压版(推荐使用解压版,所有的配置都自己操作,心中有数)

在这里插入图片描述

3.Go语言库文件夹解释

  • api : 每个版本更新说明
  • bin : 自带工具. 重点记忆
  • blog:博客
  • doc:文档
  • misc: 代码配置
  • lib:额外引用
  • src:标准库源码,以后第三方库放入到这个文件夹中. 重点记忆
  • test:测试

4.配置步骤(Windows举例)

  • 把下载好的go1.10.1.windows-amd64进行解压,解压后出现go文件夹

在这里插入图片描述

  • 把解压后的go文件夹复制到任意非中文目录中(例如: D:\mysoftware\go\soft\go)

  • 如果没有配置环境变量默认去C:\go找Go语言库

在这里插入图片描述

  • 配置环境变量

  • “我的电脑” –> 右键”属性”–> “高级” –> “环境变量” –> “系统变量”–> “新建”按钮后输入

在这里插入图片描述

  • 在”系统变量”中PATH属性里面添加%GOROOT%\bin;

在这里插入图片描述

  • 启动”命令行”输入go version如果出现下面效果说明配置成功

  • 也可以使用go env命令查看全部环境

在这里插入图片描述

5.环境变量参数解释

  • GOROOT 表示Go语言库的根目录的完整路径
  • PATH 中配置内容方便在命令行快速调用Go语言库中工具
  • GOPATH 可以先不配置,在做项目时需要配置,表示项目路径

三.Hello World

1.编写前准备

  • 在D:/盘下新建了一个文件夹,名称为go(这个文件夹名称任意,只要不是中文即可)

  • 在go文件夹下新建了一个文件夹,名称为0103,代表着这是章节1的第3小节

  • 为了能够在命令行中进行操作,需要先知道几个windows命令行命令


1
2
3
4
5
6
1盘符名:      #表示进入到某个磁盘
2cd 文件夹名称 #表示进入到文件夹中
3cd ..         #表示向上跳一个文件夹
4dir               #当前文件夹中内容展示
5
6
  • Go语言库bin目录下go.exe的run参数表示运行一个XXX.go文件


1
2
3
1go run XXX.go
2
3

2.Hello World编写过程

  • 在D:/go/0103/新建记事本,并修改扩展名后名称为main.go

  • 在文件中输入以下代码


1
2
3
4
5
6
7
8
9
1package main
2
3import "fmt"
4
5func main() {
6   fmt.Println("Hello World")
7}
8
9
  • 使用Windows命令行工具,输入以下命令运行观察结果


1
2
3
4
5
1d:
2cd go/0103
3go run main.go
4
5
  • 程序结果应该是输出


1
2
3
1Hello World
2
3

四.Hello World编写过程注意事项

1.关于文件

  • 文件名称任意,尽量使用全英文文件名

  • 文件扩展名应该为.go ,对于初学者一定要注意,以下形式都是不对了


1
2
3
4
1main.go.txt
2main.txt
3
4

2.注释

  • 注释是给程序员自己看的备注.防止忘记

  • 编译器不会编译注释中内容.注释对程序运行无影响

  • 注释支持单行注释和多行注释


1
2
3
4
5
6
7
1//单行注释 ,从双斜杠开始到这行结束的内容都是注释内容
2
3/*
4多行注释
5*/
6
7

3.package关键字

  • package表示当前代码所属的包(package),是一种组织结构.其他package通过包名调用这个包下内容
  • package是必须的,每个文件的package必须存在有效代码第一行
  • package main 是程序入口包,这个包中可以编写主函数

4.import关键字

  • import表示导入包,引用其他包的内容

  • import "fmt"表示引用fmt包

  • fmt 包是Go语言库中自带的包,实现输入输出等功能

  • import 必须存在于package关键字下面,函数或变量声明的上面

  • import 导入包时包名两侧必须有双引号,支持以下几种语法


1
2
3
4
5
6
7
8
9
10
11
1//一个包一个包的导入
2import "fmt"
3import "os"
4
5// 一次导入多个包(此方式为官方推荐的方式)
6import (
7   "fmt"
8   "os"
9)
10
11
  • Go语言要求,导入包就必须使用,否则出现编译错误.例如导入了"fmt"和"os"包,如果只使用了"fmt"会出现一下错误信息


1
2
3
1imported and not used: "os"
2
3

5.main函数

  • func main 称为主函数,是整个程序的入口,最先执行主函数中的代码

  • main()后面的 { 必须和func 在同一行,否则运行时提示下面信息


1
2
3
1.\main.go:6:syntax error:unexpected semicolon or newline before {
2
3
  • fmt.Println()后面不需要有分号,但是写分号也可以正常运行

  • 如果一行就一个语句习惯上是不写分号的

    • 如果一行有多个语句,每个语句后面要添加分号(不写推荐一行写多个)

6.编码问题

  • Go语言适用UTF-8编码,编译整个文件
  • 新建的记事本默认ANSI编码,所以要有中文需要把文件保存为UTF8编码

在这里插入图片描述

7.其他事项

  • 整个文件中严格区分大小写

五.Go工具

1.解压版Go语言安装包中自带工具

  • 在%GOROOT%/bin中有三个工具

  • go.exe 编译、运行、构建等都可以使用这个命令

    • godoc.exe 查看包或函数的源码

    • gofmt.exe 格式化文件


1
2
3
4
5
6
1--bin
2   --go.exe
3   --godoc.exe
4   --gofmt.exe
5
6

2.go.exe参数列表

  • 在命令行中通过go help查看go参数如下


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
1Usage:
2
3        go command [arguments]
4
5The commands are:
6
7        build       compile packages and dependencies
8        clean       remove object files and cached files
9        doc         show documentation for package or symbol
10        env         print Go environment information
11        bug         start a bug report
12        fix         update packages to use new APIs
13        fmt         gofmt (reformat) package sources
14        generate    generate Go files by processing source
15        get         download and install packages and dependencies
16        install     compile and install packages and dependencies
17        list        list packages
18        run         compile and run Go program
19        test        test packages
20        tool        run specified go tool
21        version     print Go version
22      vet         report likely mistakes in packages
23
24

3.常用参数解释

  • go version查看Go语言版本
  • go env查看Go语言详细环境
  • go list查看Go语言文件目录
  • go build把源码文件构建成系统可执行文件
  • go clean清空生成的可执行文件
  • go vet静态解析文件,检查是否有语法错误等
  • go get从远程下载第三方Go语言库
  • go bug提交bug
  • go test测试(在后面章节中讲解)
  • go run运行文件

六.godoc命令介绍

1.godoc 命令介绍

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

2.godoc使用

  • 查看包的源码


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
1C:\Users\zhang>godoc fmt
2use 'godoc cmd/fmt' for documentation on the fmt command
3
4PACKAGE DOCUMENTATION
5
6package fmt
7    import "fmt"
8
9    Package fmt implements formatted I/O with functions analogous to C's
10    printf and scanf. The format 'verbs' are derived from C's but are
11    simpler.
12
13
14    Printing
15
16    The verbs:
17
18    General:
19
20        %v      the value in a default format
21                when printing structs, the plus flag (%+v) adds field names
22        %#v     a Go-syntax representation of the value
23        %T      a Go-syntax representation of the type of the value
24        %%      a literal percent sign; consumes no value
25
26    Boolean:
27
28        %t      the word true or false
29
30    Integer:
31
32        %b      base 2
33        %c      the character represented by the corresponding Unicode code point
34        %d      base 10
35        %o      base 8
36        %q      a single-quoted character literal safely escaped with Go syntax.
37        %x      base 16, with lower-case letters for a-f
38        %X      base 16, with upper-case letters for A-F
39        %U      Unicode format: U+1234; same as "U+%04X"
40
41    Floating-point and complex constituents:
42
43        %b      decimalless scientific notation with exponent a power of two,
44                in the manner of strconv.FormatFloat with the 'b' format,
45                e.g. -123456p-78
46        %e      scientific notation, e.g. -1.234456e+78
47        %E      scientific notation, e.g. -1.234456E+78
48        %f      decimal point but no exponent, e.g. 123.456
49        %F      synonym for %f
50        %g      %e for large exponents, %f otherwise. Precision is discussed below.
51        %G      %E for large exponents, %F otherwise
52
53    String and slice of bytes (treated equivalently with these verbs):
54
55        %s      the uninterpreted bytes of the string or slice
56        %q      a double-quoted string safely escaped with Go syntax
57        %x      base 16, lower-case, two characters per byte
58        %X      base 16, upper-case, two characters per byte
59
60    Pointer:
61
62        %p      base 16 notation, with leading 0x
63        The %b, %d, %o, %x and %X verbs also work with pointers,
64        formatting the value exactly as if it were an integer.
65
66    The default format for %v is:
67
68        bool:                    %t
69        int, int8 etc.:          %d
70        uint, uint8 etc.:        %d, %#x if printed with %#v
71        float32, complex64, etc: %g
72        string:                  %s
73        chan:                    %p
74        pointer:                 %p
75
76    For compound objects, the elements are printed using these rules,
77    recursively, laid out like this:
78
79        struct:             {field0 field1 ...}
80        array, slice:       [elem0 elem1 ...]
81        maps:               map[key1:value1 key2:value2]
82        pointer to above:   &{}, &[], &map[]
83
84    Width is specified by an optional decimal number immediately preceding
85    the verb. If absent, the width is whatever is necessary to represent the
86    value. Precision is specified after the (optional) width by a period
87    followed by a decimal number. If no period is present, a default
88    precision is used. A period with no following number specifies a
89    precision of zero. Examples:
90
91        %f     default width, default precision
92        %9f    width 9, default precision
93        %.2f   default width, precision 2
94        %9.2f  width 9, precision 2
95        %9.f   width 9, precision 0
96
97    Width and precision are measured in units of Unicode code points, that
98    is, runes. (This differs from C's printf where the units are always
99    measured in bytes.) Either or both of the flags may be replaced with the
100    character '*', causing their values to be obtained from the next operand
101    (preceding the one to format), which must be of type int.
102
103    For most values, width is the minimum number of runes to output, padding
104    the formatted form with spaces if necessary.
105
106    For strings, byte slices and byte arrays, however, precision limits the
107    length of the input to be formatted (not the size of the output),
108    truncating if necessary. Normally it is measured in runes, but for these
109    types when formatted with the %x or %X format it is measured in bytes.
110
111    For floating-point values, width sets the minimum width of the field and
112    precision sets the number of places after the decimal, if appropriate,
113    except that for %g/%G precision sets the total number of significant
114    digits. For example, given 12.345 the format %6.3f prints 12.345 while
115    %.3g prints 12.3. The default precision for %e, %f and %#g is 6; for %g
116    it is the smallest number of digits necessary to identify the value
117    uniquely.
118
119    For complex numbers, the width and precision apply to the two components
120    independently and the result is parenthesized, so %f applied to 1.2+3.4i
121    produces (1.200000+3.400000i).
122
123    Other flags:
124
125        +       always print a sign for numeric values;
126                guarantee ASCII-only output for %q (%+q)
127        -       pad with spaces on the right rather than the left (left-justify the field)
128        #       alternate format: add leading 0 for octal (%#o), 0x for hex (%#x);
129                0X for hex (%#X); suppress 0x for %p (%#p);
130                for %q, print a raw (backquoted) string if strconv.CanBackquote
131                returns true;
132                always print a decimal point for %e, %E, %f, %F, %g and %G;
133                do not remove trailing zeros for %g and %G;
134                write e.g. U+0078 'x' if the character is printable for %U (%#U).
135        ' '     (space) leave a space for elided sign in numbers (% d);
136                put spaces between bytes printing strings or slices in hex (% x, % X)
137        0       pad with leading zeros rather than spaces;
138                for numbers, this moves the padding after the sign
139
140    Flags are ignored by verbs that do not expect them. For example there is
141    no alternate decimal format, so %#d and %d behave identically.
142
143    For each Printf-like function, there is also a Print function that takes
144    no format and is equivalent to saying %v for every operand. Another
145    variant Println inserts blanks between operands and appends a newline.
146
147    Regardless of the verb, if an operand is an interface value, the
148    internal concrete value is used, not the interface itself. Thus:
149
150        var i interface{} = 23
151        fmt.Printf("%v\n", i)
152
153    will print 23.
154
155    Except when printed using the verbs %T and %p, special formatting
156    considerations apply for operands that implement certain interfaces. In
157    order of application:
158
159    1. If the operand is a reflect.Value, the operand is replaced by the
160    concrete value that it holds, and printing continues with the next rule.
161
162    2. If an operand implements the Formatter interface, it will be invoked.
163    Formatter provides fine control of formatting.
164
165    3. If the %v verb is used with the # flag (%#v) and the operand
166    implements the GoStringer interface, that will be invoked.
167
168    If the format (which is implicitly %v for Println etc.) is valid for a
169    string (%s %q %v %x %X), the following two rules apply:
170
171    4. If an operand implements the error interface, the Error method will
172    be invoked to convert the object to a string, which will then be
173    formatted as required by the verb (if any).
174
175    5. If an operand implements method String() string, that method will be
176    invoked to convert the object to a string, which will then be formatted
177    as required by the verb (if any).
178
179    For compound operands such as slices and structs, the format applies to
180    the elements of each operand, recursively, not to the operand as a
181    whole. Thus %q will quote each element of a slice of strings, and %6.2f
182    will control formatting for each element of a floating-point array.
183
184    However, when printing a byte slice with a string-like verb (%s %q %x
185    %X), it is treated identically to a string, as a single item.
186
187    To avoid recursion in cases such as
188
189        type X string
190        func (x X) String() string { return Sprintf("<%s>", x) }
191
192    convert the value before recurring:
193
194        func (x X) String() string { return Sprintf("<%s>", string(x)) }
195
196    Infinite recursion can also be triggered by self-referential data
197    structures, such as a slice that contains itself as an element, if that
198    type has a String method. Such pathologies are rare, however, and the
199    package does not protect against them.
200
201    When printing a struct, fmt cannot and therefore does not invoke
202    formatting methods such as Error or String on unexported fields.
203
204    Explicit argument indexes:
205
206    In Printf, Sprintf, and Fprintf, the default behavior is for each
207    formatting verb to format successive arguments passed in the call.
208    However, the notation [n] immediately before the verb indicates that the
209    nth one-indexed argument is to be formatted instead. The same notation
210    before a '*' for a width or precision selects the argument index holding
211    the value. After processing a bracketed expression [n], subsequent verbs
212    will use arguments n+1, n+2, etc. unless otherwise directed.
213
214    For example,
215
216        fmt.Sprintf("%[2]d %[1]d\n", 11, 22)
217
218    will yield "22 11", while
219
220        fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6)
221
222    equivalent to
223
224        fmt.Sprintf("%6.2f", 12.0)
225
226    will yield " 12.00". Because an explicit index affects subsequent verbs,
227    this notation can be used to print the same values multiple times by
228    resetting the index for the first argument to be repeated:
229
230        fmt.Sprintf("%d %d %#[1]x %#x", 16, 17)
231
232    will yield "16 17 0x10 0x11".
233
234    Format errors:
235
236    If an invalid argument is given for a verb, such as providing a string
237    to %d, the generated string will contain a description of the problem,
238    as in these examples:
239
240        Wrong type or unknown verb: %!verb(type=value)
241                Printf("%d", hi):          %!d(string=hi)
242        Too many arguments: %!(EXTRA type=value)
243                Printf("hi", "guys"):      hi%!(EXTRA string=guys)
244        Too few arguments: %!verb(MISSING)
245                Printf("hi%d"):            hi%!d(MISSING)
246        Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
247                Printf("%*s", 4.5, "hi"):  %!(BADWIDTH)hi
248                Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
249        Invalid or invalid use of argument index: %!(BADINDEX)
250                Printf("%*[2]d", 7):       %!d(BADINDEX)
251                Printf("%.[2]d", 7):       %!d(BADINDEX)
252
253    All errors begin with the string "%!" followed sometimes by a single
254    character (the verb) and end with a parenthesized description.
255
256    If an Error or String method triggers a panic when called by a print
257    routine, the fmt package reformats the error message from the panic,
258    decorating it with an indication that it came through the fmt package.
259    For example, if a String method calls panic("bad"), the resulting
260    formatted message will look like
261
262        %!s(PANIC=bad)
263
264    The %!s just shows the print verb in use when the failure occurred. If
265    the panic is caused by a nil receiver to an Error or String method,
266    however, the output is the undecorated string, "<nil>".
267
268
269    Scanning
270
271    An analogous set of functions scans formatted text to yield values.
272    Scan, Scanf and Scanln read from os.Stdin; Fscan, Fscanf and Fscanln
273    read from a specified io.Reader; Sscan, Sscanf and Sscanln read from an
274    argument string.
275
276    Scan, Fscan, Sscan treat newlines in the input as spaces.
277
278    Scanln, Fscanln and Sscanln stop scanning at a newline and require that
279    the items be followed by a newline or EOF.
280
281    Scanf, Fscanf, and Sscanf parse the arguments according to a format
282    string, analogous to that of Printf. In the text that follows, 'space'
283    means any Unicode whitespace character except newline.
284
285    In the format string, a verb introduced by the % character consumes and
286    parses input; these verbs are described in more detail below. A
287    character other than %, space, or newline in the format consumes exactly
288    that input character, which must be present. A newline with zero or more
289    spaces before it in the format string consumes zero or more spaces in
290    the input followed by a single newline or the end of the input. A space
291    following a newline in the format string consumes zero or more spaces in
292    the input. Otherwise, any run of one or more spaces in the format string
293    consumes as many spaces as possible in the input. Unless the run of
294    spaces in the format string appears adjacent to a newline, the run must
295    consume at least one space from the input or find the end of the input.
296
297    The handling of spaces and newlines differs from that of C's scanf
298    family: in C, newlines are treated as any other space, and it is never
299    an error when a run of spaces in the format string finds no spaces to
300    consume in the input.
301
302    The verbs behave analogously to those of Printf. For example, %x will
303    scan an integer as a hexadecimal number, and %v will scan the default
304    representation format for the value. The Printf verbs %p and %T and the
305    flags # and + are not implemented, and the verbs %e %E %f %F %g and %G
306    are all equivalent and scan any floating-point or complex value.
307
308    Input processed by verbs is implicitly space-delimited: the
309    implementation of every verb except %c starts by discarding leading
310    spaces from the remaining input, and the %s verb (and %v reading into a
311    string) stops consuming input at the first space or newline character.
312
313    The familiar base-setting prefixes 0 (octal) and 0x (hexadecimal) are
314    accepted when scanning integers without a format or with the %v verb.
315
316    Width is interpreted in the input text but there is no syntax for
317    scanning with a precision (no %5.2f, just %5f). If width is provided, it
318    applies after leading spaces are trimmed and specifies the maximum
319    number of runes to read to satisfy the verb. For example,
320
321        Sscanf(" 1234567 ", "%5s%d", &s, &i)
322
323    will set s to "12345" and i to 67 while
324
325        Sscanf(" 12 34 567 ", "%5s%d", &s, &i)
326
327    will set s to "12" and i to 34.
328
329    In all the scanning functions, a carriage return followed immediately by
330    a newline is treated as a plain newline (\r\n means the same as \n).
331
332    In all the scanning functions, if an operand implements method Scan
333    (that is, it implements the Scanner interface) that method will be used
334    to scan the text for that operand. Also, if the number of arguments
335    scanned is less than the number of arguments provided, an error is
336    returned.
337
338    All arguments to be scanned must be either pointers to basic types or
339    implementations of the Scanner interface.
340
341    Like Scanf and Fscanf, Sscanf need not consume its entire input. There
342    is no way to recover how much of the input string Sscanf used.
343
344    Note: Fscan etc. can read one character (rune) past the input they
345    return, which means that a loop calling a scan routine may skip some of
346    the input. This is usually a problem only when there is no space between
347    input values. If the reader provided to Fscan implements ReadRune, that
348    method will be used to read characters. If the reader also implements
349    UnreadRune, that method will be used to save the character and
350    successive calls will not lose data. To attach ReadRune and UnreadRune
351    methods to a reader without that capability, use bufio.NewReader.
352
353FUNCTIONS
354
355func Errorf(format string, a ...interface{}) error
356    Errorf formats according to a format specifier and returns the string as
357    a value that satisfies error.
358
359func Fprint(w io.Writer, a ...interface{}) (n int, err error)
360    Fprint formats using the default formats for its operands and writes to
361    w. Spaces are added between operands when neither is a string. It
362    returns the number of bytes written and any write error encountered.
363
364func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)
365    Fprintf formats according to a format specifier and writes to w. It
366    returns the number of bytes written and any write error encountered.
367
368func Fprintln(w io.Writer, a ...interface{}) (n int, err error)
369    Fprintln formats using the default formats for its operands and writes
370    to w. Spaces are always added between operands and a newline is
371    appended. It returns the number of bytes written and any write error
372    encountered.
373
374func Fscan(r io.Reader, a ...interface{}) (n int, err error)
375    Fscan scans text read from r, storing successive space-separated values
376    into successive arguments. Newlines count as space. It returns the
377    number of items successfully scanned. If that is less than the number of
378    arguments, err will report why.
379
380func Fscanf(r io.Reader, format string, a ...interface{}) (n int, err error)
381    Fscanf scans text read from r, storing successive space-separated values
382    into successive arguments as determined by the format. It returns the
383    number of items successfully parsed. Newlines in the input must match
384    newlines in the format.
385
386func Fscanln(r io.Reader, a ...interface{}) (n int, err error)
387    Fscanln is similar to Fscan, but stops scanning at a newline and after
388    the final item there must be a newline or EOF.
389
390func Print(a ...interface{}) (n int, err error)
391    Print formats using the default formats for its operands and writes to
392    standard output. Spaces are added between operands when neither is a
393    string. It returns the number of bytes written and any write error
394    encountered.
395
396func Printf(format string, a ...interface{}) (n int, err error)
397    Printf formats according to a format specifier and writes to standard
398    output. It returns the number of bytes written and any write error
399    encountered.
400
401func Println(a ...interface{}) (n int, err error)
402    Println formats using the default formats for its operands and writes to
403    standard output. Spaces are always added between operands and a newline
404    is appended. It returns the number of bytes written and any write error
405    encountered.
406
407func Scan(a ...interface{}) (n int, err error)
408    Scan scans text read from standard input, storing successive
409    space-separated values into successive arguments. Newlines count as
410    space. It returns the number of items successfully scanned. If that is
411    less than the number of arguments, err will report why.
412
413func Scanf(format string, a ...interface{}) (n int, err error)
414    Scanf scans text read from standard input, storing successive
415    space-separated values into successive arguments as determined by the
416    format. It returns the number of items successfully scanned. If that is
417    less than the number of arguments, err will report why. Newlines in the
418    input must match newlines in the format. The one exception: the verb %c
419    always scans the next rune in the input, even if it is a space (or tab
420    etc.) or newline.
421
422func Scanln(a ...interface{}) (n int, err error)
423    Scanln is similar to Scan, but stops scanning at a newline and after the
424    final item there must be a newline or EOF.
425
426func Sprint(a ...interface{}) string
427    Sprint formats using the default formats for its operands and returns
428    the resulting string. Spaces are added between operands when neither is
429    a string.
430
431func Sprintf(format string, a ...interface{}) string
432    Sprintf formats according to a format specifier and returns the
433    resulting string.
434
435func Sprintln(a ...interface{}) string
436    Sprintln formats using the default formats for its operands and returns
437    the resulting string. Spaces are always added between operands and a
438    newline is appended.
439
440func Sscan(str string, a ...interface{}) (n int, err error)
441    Sscan scans the argument string, storing successive space-separated
442    values into successive arguments. Newlines count as space. It returns
443    the number of items successfully scanned. If that is less than the
444    number of arguments, err will report why.
445
446func Sscanf(str string, format string, a ...interface{}) (n int, err error)
447    Sscanf scans the argument string, storing successive space-separated
448    values into successive arguments as determined by the format. It returns
449    the number of items successfully parsed. Newlines in the input must
450    match newlines in the format.
451
452func Sscanln(str string, a ...interface{}) (n int, err error)
453    Sscanln is similar to Sscan, but stops scanning at a newline and after
454    the final item there must be a newline or EOF.
455
456TYPES
457
458type Formatter interface {
459    Format(f State, c rune)
460}
461    Formatter is the interface implemented by values with a custom
462    formatter. The implementation of Format may call Sprint(f) or Fprint(f)
463    etc. to generate its output.
464
465type GoStringer interface {
466    GoString() string
467}
468    GoStringer is implemented by any value that has a GoString method, which
469    defines the Go syntax for that value. The GoString method is used to
470    print values passed as an operand to a %#v format.
471
472type ScanState interface {
473    // ReadRune reads the next rune (Unicode code point) from the input.
474    // If invoked during Scanln, Fscanln, or Sscanln, ReadRune() will
475    // return EOF after returning the first '\n' or when reading beyond
476    // the specified width.
477    ReadRune() (r rune, size int, err error)
478    // UnreadRune causes the next call to ReadRune to return the same rune.
479    UnreadRune() error
480    // SkipSpace skips space in the input. Newlines are treated appropriately
481    // for the operation being performed; see the package documentation
482    // for more information.
483    SkipSpace()
484    // Token skips space in the input if skipSpace is true, then returns the
485    // run of Unicode code points c satisfying f(c).  If f is nil,
486    // !unicode.IsSpace(c) is used; that is, the token will hold non-space
487    // characters. Newlines are treated appropriately for the operation being
488    // performed; see the package documentation for more information.
489    // The returned slice points to shared data that may be overwritten
490    // by the next call to Token, a call to a Scan function using the ScanState
491    // as input, or when the calling Scan method returns.
492    Token(skipSpace bool, f func(rune) bool) (token []byte, err error)
493    // Width returns the value of the width option and whether it has been set.
494    // The unit is Unicode code points.
495    Width() (wid int, ok bool)
496    // Because ReadRune is implemented by the interface, Read should never be
497    // called by the scanning routines and a valid implementation of
498    // ScanState may choose always to return an error from Read.
499    Read(buf []byte) (n int, err error)
500}
501    ScanState represents the scanner state passed to custom scanners.
502    Scanners may do rune-at-a-time scanning or ask the ScanState to discover
503    the next space-delimited token.
504
505type Scanner interface {
506    Scan(state ScanState, verb rune) error
507}
508    Scanner is implemented by any value that has a Scan method, which scans
509    the input for the representation of a value and stores the result in the
510    receiver, which must be a pointer to be useful. The Scan method is
511    called for any argument to Scan, Scanf, or Scanln that implements it.
512
513type State interface {
514    // Write is the function to call to emit formatted output to be printed.
515    Write(b []byte) (n int, err error)
516    // Width returns the value of the width option and whether it has been set.
517    Width() (wid int, ok bool)
518    // Precision returns the value of the precision option and whether it has been set.
519    Precision() (prec int, ok bool)
520
521    // Flag reports whether the flag c, a character, has been set.
522    Flag(c int) bool
523}
524    State represents the printer state passed to custom formatters. It
525    provides access to the io.Writer interface plus information about the
526    flags and options for the operand's format specifier.
527
528type Stringer interface {
529    String() string
530}
531    Stringer is implemented by any value that has a String method, which
532    defines the ``native'' format for that value. The String method is used
533    to print values passed as an operand to any format that accepts a string
534    or to an unformatted printer such as Print.
535
536
  • 查看某个包中某个函数


1
2
3
4
5
6
7
8
9
10
1C:\Users\zhang>godoc fmt Println
2use 'godoc cmd/fmt' for documentation on the fmt command
3
4func Println(a ...interface{}) (n int, err error)
5    Println formats using the default formats for its operands and writes to
6    standard output. Spaces are always added between operands and a newline
7    is appended. It returns the number of bytes written and any write error
8    encountered.
9
10

七.gofmt工具

1.gofmt工具介绍

  • 规范的代码方便自己的阅读也方便别人的阅读.编写规范代码是每个程序的必修课
  • gofmt工具可以帮助程序员把代码进行格式化,按照规范进行格式化
  • 使用gofmt前提是文件编译通过

2. 不规范代码示例

  • 查看下面代码中不规范的地方有几处


1
2
3
4
5
6
7
1package main
2import "fmt"
3func main ( ){
4fmt.Println("hello word");
5}
6
7

3.使用gofmt的步骤

  • 在命令行输入gofmt 文件名就可以对文件进行格式化,格式化后输出


1
2
3
4
5
6
7
8
9
10
1D:\go\0201>gofmt main.go
2package main
3
4import "fmt"
5
6func main() {
7        fmt.Println("hello word")
8}
9
10
  • 通过运行gofmt后发现规范的代码和不规范代码的几处区别

  • package关键字和import关键字和func main之间有空行

    • main和括号之间没有空格
    • main后面()之间没有空格
    • ()和{之间有空格
    • fmt.Println()前面有缩进
    • fmt.Println()后面没有分号

「点点赞赏,手留余香」

    还没有人赞赏,快来当第一个赞赏的人吧!