- 快召唤伙伴们来围观吧
- 微博 QQ QQ空间 贴吧
- 文档嵌入链接
- 复制
- 微信扫一扫分享
- 已成功复制到剪贴板
Effective Go中英双语版
展开查看详情
1 .
2 . Table of Contents 前言 1.1 引言 1.2 格式化 1.3 注释 1.4 命名 1.5 分号 1.6 控制结构 1.7 函数 1.8 数据 1.9 初始化 1.10 方法 1.11 接口和其他类型 1.12 空白标识符 1.13 内嵌 1.14 并发 1.15 错误 1.16 一个Web服务器 1.17 2
3 .前言 《Effective Go》中英双语版 Effective Go - 《实效 GO 编程》 Introduction Go is a new language. Although it borrows ideas from existing languages, it has unusual properties that make effective Go programs different in character from programs written in its relatives. A straightforward translation of a C++ or Java program into Go is unlikely to produce a satisfactory result—Java programs are written in Java, not Go. On the other hand, thinking about the problem from a Go perspective could produce a successful but quite different program. In other words, to write Go well, it's important to understand its properties and idioms. It's also important to know the established conventions for programming in Go, such as naming, formatting, program construction, and so on, so that programs you write will be easy for other Go programmers to understand. This document gives tips for writing clear, idiomatic Go code. It augments the language specification, the Tour of Go, and How to Write Go Code, all of which you should read first. 引言 Go 是一门全新的语言。尽管它从既有的语言中借鉴了许多理念,但其与众不同的特性,使得 用 Go 编程在本质上就不同于其它语言。将现有的 C++ 或 Java 程序直译为 Go 程序并不能令 人满意——毕竟 Java 程序是用 Java 编写的,而不是 Go。 另一方面,若从 Go 的角度去分 析问题,你就能编写出同样可行但大不相同的程序。 换句话说,要想将 Go 程序写得好,就 必须理解其特性和风格。了解命名、格式化、程序结构等既定规则也同样重要,这样你编写 的程序才能更容易被其他程序员所理解。 本文档就如何编写清晰、地道的 Go 代码提供了一些技巧。它是对 语言规范、 Go 语言之旅 以及 如何使用 Go 编程 的补充说明,因此我们建议您先阅读这些文档。 Effective Go 作为 GO 语言的入门必读教程,值得每位初学者好好阅读一遍,编辑成书,方 便阅读交流。 当前完成章节(全部完成): 1. 前言 3
4 .前言 2. 引言 3. 格式化 4. 注释 5. 命名 6. 分号 7. 控制结构 8. 函数 9. 数据 10. 初始化 11. 方法 12. 接口和其他类型 13. 空白标识符 14. 内嵌 15. 并发 16. 错误 17. 一个 Web 服务器 改版说明:@2016.8.6 by bingoHuang, revision to Chinese & English version. 李笑来在他的新书 《人人都是工程师》 中说过一句话: 在中国,对绝大多数人来 说, English + Computer Skills = Freedom (英语 + 计算机技能 = 自由) 我非常的赞同。英语和计算机技能是相辅相成,学习好一门编程语言(如 Go )的同 时,还能加强英语学习,何乐而不为。所以我决定将本书改版成中英双语版,方便更多 的人来学习阅读。 特别感谢 Golang 官网提供的英文版教程。 感谢 hellogcc 提供的 中文翻译版一,这是我之前制作中文版电子书所参考的资料,翻译 的很用心。 要更感谢 Go 语言中文社区 提供的 中文翻译版二,此翻译更贴切有味道,不可多得。本 人已和 Go-zh 项目组 沟通过,获取了该社区的授权,故将此作为双语版的中文版本。 参考 参考官方英文版:Effective Go 英文版 参考中文翻译版一:Effective Go 中文版 参考中文翻译版二:Effective Go 中文版 Read, Fork and Star 4
5 .前言 Read on Gitbook Fork on GitHub 请顺手点一下 STAT ,或者留言讨论,这是对我最大的鼓励! License 除特别注明外, 本页内容均采用知识共享 - 署名(CC-BY)3.0 协议授权,代码采用 BSD 协 议 授权。 5
6 .引言 Introduction 引言 Go is a new language. Although it borrows ideas from existing languages, it has unusual properties that make effective Go programs different in character from programs written in its relatives. A straightforward translation of a C++ or Java program into Go is unlikely to produce a satisfactory result—Java programs are written in Java, not Go. On the other hand, thinking about the problem from a Go perspective could produce a successful but quite different program. In other words, to write Go well, it's important to understand its properties and idioms. It's also important to know the established conventions for programming in Go, such as naming, formatting, program construction, and so on, so that programs you write will be easy for other Go programmers to understand. Go 是一门全新的语言。尽管它从既有的语言中借鉴了许多理念,但其与众不同的特性, 使得 使用 Go 编程在本质上就不同于其它语言。将现有的 C++ 或 Java 程序直译为 Go 程序并不能 令人满意——毕竟 Java 程序是用 Java 编写的,而不是 Go。 另一方面,若从 Go 的角度去 分析问题,你就能编写出同样可行但大不相同的程序。 换句话说,要想将 Go 程序写得好, 就必须理解其特性和风格。了解命名、格式化、 程序结构等既定规则也同样重要,这样你编 写的程序才能更容易被其他程序员所理解。 This document gives tips for writing clear, idiomatic Go code. It augments the language specification, the Tour of Go, and How to Write Go Code, all of which you should read first. 本文档就如何编写清晰、地道的 Go 代码提供了一些技巧。它是对 语言规范、 Go 语言之旅 以及 如何使用 Go 编程 的补充说明,因此我们建议您先阅读这些文档。 Examples 示例 The Go package sources are intended to serve not only as the core library but also as examples of how to use the language. Moreover, many of the packages contain working, self-contained executable examples you can run directly from the golang.org web site, such as this one (if necessary, click on the word"Example"to open it up). If you have a question about how to approach a problem or how something might be implemented, the documentation, code and examples in the library can provide answers, ideas and background. 6
7 .引言 Go 包的源码 不仅是核心库,同时也是学习如何使用 Go 语言的示例源码。 此外,其中的一 些包还包含了可工作的,独立的可执行示例,你可以直接在 golang.org 网站上运行它们,比 如 这个例子 (单击文字 “示例” 来展开它)。如果你有任何关于某些问题如何解决,或某些东 西如何实现的疑问, 也可以从中获取相关的答案、思路以及后台实现。 7
8 .格式化 Formatting 格式化 Formatting issues are the most contentious but the least consequential. People can adapt to different formatting styles but it's better if they don't have to, and less time is devoted to the topic if everyone adheres to the same style. The problem is how to approach this Utopia without a long prescriptive style guide. 格式化问题总是充满了争议,但却始终没有形成统一的定论。虽说人们可以适应不同的编码 风格, 但抛弃这种适应过程岂不更好?若所有人都遵循相同的编码风格,在这类问题上浪费 的时间将会更少。 问题就在于如何实现这种设想,而无需冗长的语言风格规范。 With Go we take an unusual approach and let the machine take care of most formatting issues. The gofmt program (also available as go fmt, which operates at the package level rather than source file level) reads a Go program and emits the source in a standard style of indentation and vertical alignment, retaining and if necessary reformatting comments. If you want to know how to handle some new layout situation, run gofmt; if the answer doesn't seem right, rearrange your program (or file a bug about gofmt), don't work around it. 在 Go 中我们另辟蹊径,让机器来处理大部分的格式化问题。gofmt 程序(也可用 go fmt,它 以包为处理对象而非源文件)将 Go 程序按照标准风格缩进、 对齐,保留注释并在需要时重 新格式化。若你想知道如何处理一些新的代码布局,请尝试运行 gofmt;若结果仍不尽人意, 请重新组织你的程序(或提交有关 gofmt 的 Bug),而不必为此纠结。 As an example, there's no need to spend time lining up the comments on the fields of a structure. Gofmt will do that for you. Given the declaration 举例来说,你无需花时间将结构体中的字段注释对齐,gofmt 将为你代劳。 假如有以下声 明: type T struct { name string // name of the object value int // its value } type T struct { name string // 对象名 value int // 对象值 } 8
9 .格式化 gofmt will line up the columns: gofmt 会将它按列对齐为: type T struct { name string // name of the object value int // its value } type T struct { name string // 对象名 value int // 对象值 } All Go code in the standard packages has been formatted with gofmt. 标准包中所有的 Go 代码都已经用 gofmt 格式化过了。 Some formatting details remain. Very briefly: 还有一些关于格式化的细节,它们非常简短: Indentation We use tabs for indentation and gofmt emits them by default. Use spaces only if you must. Line length Go has no line length limit. Don't worry about overflowing a punched card. If a line feels too long, wrap it and indent with an extra tab. Parentheses Go needs fewer parentheses than C and Java: control structures (if, for, switch) do not have parentheses in their syntax. Also, the operator precedence hierarchy is short er and clearer, so x<<8 + y<<16 means what the spacing implies, unlike in the other languages. 缩进 我们使用制表符(tab)缩进,gofmt 默认也使用它。在你认为确实有必要时再使用空格。 行的长度 Go 对行的长度没有限制,别担心打孔纸不够长。如果一行实在太长,也可进行折行并插入适当的 tab 缩进。 括号 比起 C 和 Java,Go 所需的括号更少:控制结构(if、for 和 switch)在语法上并不需要圆括号。此外,操 作符优先级处理变得更加简洁,因此 x<<8 + y<<16 正表述了空格符所传达的含义。 9
10 .格式化 10
11 .注释 Commentary 注释 Go provides C-style /* */ block comments and C++-style // line comments. Line comments are the norm; block comments appear mostly as package comments, but are useful within an expression or to disable large swaths of code. Go 语言支持 C 风格的块注释 /* */ 和 C++ 风格的行注释 // 。 行注释更为常用,而块注 释则主要用作包的注释,当然也可在禁用一大段代码时使用。 The program—and web server—godoc processes Go source files to extract documentation about the contents of the package. Comments that appear before top-level declarations, with no intervening newlines, are extracted along with the declaration to serve as explanatory text for the item. The nature and style of these comments determines the quality of the documentation godoc produces. godoc 既是一个程序,又是一个 Web 服务器,它对 Go 的源码进行处理,并提取包中的文档 内容。 出现在顶级声明之前,且与该声明之间没有空行的注释,将与该声明一起被提取出 来,作为该条目的说明文档。 这些注释的类型和风格决定了 godoc 生成的文档质量。 Every package should have a package comment, a block comment preceding the package clause. For multi-file packages, the package comment only needs to be present in one file, and any one will do. The package comment should introduce the package and provide information relevant to the package as a whole. It will appear first on the godoc page and should set up the detailed documentation that follows. 每个包都应包含一段包注释,即放置在包子句前的一个块注释。对于包含多个文件的包, 包 注释只需出现在其中的任一文件中即可。包注释应在整体上对该包进行介绍,并提供包的相 关信息。 它将出现在 godoc 页面中的最上面,并为紧随其后的内容建立详细的文档。 11
12 .注释 /* Package regexp implements a simple library for regular expressions. The syntax of the regular expressions accepted is: regexp: concatenation { '|' concatenation } concatenation: { closure } closure: term [ '*' | '+' | '?' ] term: '^' '$' '.' character '[' [ '^' ] character-ranges ']' '(' regexp ')' */ package regexp /* regexp 包为正则表达式实现了一个简单的库。 该库接受的正则表达式语法为: 正则表达式: 串联 { '|' 串联 } 串联: { 闭包 } 闭包: 条目 [ '*' | '+' | '?' ] 条目: '^' '$' '.' 字符 '[' [ '^' ] 字符遍历 ']' '(' 正则表达式 ')' */ package regexp If the package is simple, the package comment can be brief. 若某个包比较简单,包注释同样可以简洁些。 // Package path implements utility routines for // manipulating slash-separated filename paths. 12
13 .注释 // path 包实现了一些常用的工具,以便于操作用反斜杠分隔的路径. Comments do not need extra formatting such as banners of stars. The generated output may not even be presented in a fixed-width font, so don't depend on spacing for alignment— godoc, like gofmt, takes care of that. The comments are uninterpreted plain text, so HTML and other annotations such as _this_ will reproduce verbatim and should not be used. One adjustment godoc does do is to display indented text in a fixed-width font, suitable for program snippets. The package comment for the fmt package uses this to good effect. 注释无需进行额外的格式化,如用星号来突出等。生成的输出甚至可能无法以等宽字体显 示, 因此不要依赖于空格对齐,godoc 会像 gofmt 那样处理好这一切。 注释是不会被解析的 纯文本,因此像 HTML 或其它类似于 _这样_ 的东西将按照 原样 输出,因此不应使用它们。 godoc 所做的调整, 就是将已缩进的文本以等宽字体显示,来适应对应的程序片段。 fmt 包 的注释就用了这种不错的效果。 Depending on the context, godoc might not even reformat comments, so make sure they look good straight up: use correct spelling, punctuation, and sentence structure, fold long lines, and so on. godoc 是否会重新格式化注释取决于上下文,因此必须确保它们看起来清晰易辨: 使用正确 的拼写、标点和语句结构以及折叠长行等。 Inside a package, any comment immediately preceding a top-level declaration serves as a doc comment for that declaration. Every exported (capitalized) name in a program should have a doc comment. 在包中,任何顶级声明前面的注释都将作为该声明的文档注释。 在程序中,每个可导出(首 字母大写)的名称都应该有文档注释。 Doc comments work best as complete sentences, which allow a wide variety of automated presentations. The first sentence should be a one-sentence summary that starts with the name being declared. 文档注释最好是完整的句子,这样它才能适应各种自动化的展示。 第一句应当以被声明的东 西开头,并且是单句的摘要。 // Compile parses a regular expression and returns, if successful, a Regexp // object that can be used to match against text. func Compile(str string) (regexp *Regexp, err error) { // Compile 用于解析正则表达式并返回,如果成功,则 Regexp 对象就可用于匹配所针对的文本。 func Compile(str string) (regexp *Regexp, err error) { 13
14 .注释 If the name always begins the comment, the output of godoc can usefully be run through grep. Imagine you couldn't remember the name"Compile" but were looking for the parsing function for regular expressions, so you ran the command, 若注释总是以名称开头,godoc 的输出就能通过 grep 变得更加有用。假如你记不住 “Compile” 这个名称,而又在找正则表达式的解析函数, 那就可以运行 $ godoc regexp | grep parse If all the doc comments in the package began, "This function...", grep wouldn't help you remember the name. But because the package starts each doc comment with the name, you'd see something like this, which recalls the word you're looking for. 若包中的所有文档注释都以 “此函数…” 开头,grep 就无法帮你记住此名称。 但由于每个包的 文档注释都以其名称开头,你就能看到这样的内容,它能显示你正在寻找的词语。 $ godoc regexp | grep parse Compile parses a regular expression and returns, if successful, a Regexp parsed. It simplifies safe initialization of global variables holding cannot be parsed. It simplifies safe initialization of global variables $ Go's declaration syntax allows grouping of declarations. A single doc comment can introduce a group of related constants or variables. Since the whole declaration is presented, such a comment can often be perfunctory. Go的声明语法允许成组声明。单个文档注释应介绍一组相关的常量或变量。 由于是整体声 明,这种注释往往较为笼统。 // Error codes returned by failures to parse an expression. var ( ErrInternal = errors.New("regexp: internal error") ErrUnmatchedLpar = errors.New("regexp: unmatched '('") ErrUnmatchedRpar = errors.New("regexp: unmatched ')'") ... ) // 表达式解析失败后返回错误代码。 var ( ErrInternal = errors.New("regexp: internal error") ErrUnmatchedLpar = errors.New("regexp: unmatched '('") ErrUnmatchedRpar = errors.New("regexp: unmatched ')'") ... ) 14
15 .注释 Grouping can also indicate relationships between items, such as the fact that a set of variables is protected by a mutex. 即便是对于私有名称,也可通过成组声明来表明各项间的关系,例如某一组由互斥体保护的 变量。 var ( countLock sync.Mutex inputCount uint32 outputCount uint32 errorCount uint32 ) 15
16 .命名 Names 命名 Names are as important in Go as in any other language. They even have semantic effect: the visibility of a name outside a package is determined by whether its first character is upper case. It's therefore worth spending a little time talking about naming conventions in Go programs. 正如命名在其它语言中的地位,它在 Go 中同样重要。有时它们甚至会影响语义: 例如,某 个名称在包外是否可见,就取决于其首个字符是否为大写字母。 因此有必要花点时间来讨论 Go 程序中的命名约定。 Package names 包名 When a package is imported, the package name becomes an accessor for the contents. After 当一个包被导入后,包名就会成了内容的访问器。在 import "bytes" the importing package can talk about bytes.Buffer. It's helpful if everyone using the package can use the same name to refer to its contents, which implies that the package name should be good: short, concise, evocative. By convention, packages are given lower case, single- word names; there should be no need for underscores or mixedCaps. Err on the side of brevity, since everyone using your package will be typing that name. And don't worry about collisions a priori. The package name is only the default name for imports; it need not be unique across all source code, and in the rare case of a collision the importing package can choose a different name to use locally. In any case, confusion is rare because the file name in the import determines just which package is being used. 之后,被导入的包就能通过 bytes.Buffer 来引用了。 若所有人都以相同的名称来引用其内容 将大有裨益, 这也就意味着包应当有个恰当的名称:其名称应该简洁明了而易于理解。按照 惯例, 包应当以小写的单个单词来命名,且不应使用下划线或驼峰记法。err 的命名就是出于 简短考虑的,因为任何使用该包的人都会键入该名称。 不必担心引用次序的冲突。包名就是 16
17 .命名 导入时所需的唯一默认名称, 它并不需要在所有源码中保持唯一,即便在少数发生冲突的情 况下, 也可为导入的包选择一个别名来局部使用。 无论如何,通过文件名来判定使用的包, 都是不会产生混淆的。 Another convention is that the package name is the base name of its source directory; the package in src/encoding/base64 is imported as "encoding/base64" but has name base64, not encoding_base64 and not encodingBase64. 另一个约定就是包名应为其源码目录的基本名称。在 src/pkg/encoding/base64 中的包应作为 "encoding/base64" 导入,其包名应为 base64, 而非 encoding_base64 或 encodingBase64。 The importer of a package will use the name to refer to its contents, so exported names in the package can use that fact to avoid stutter. (Don't use the import . notation, which can simplify tests that must run outside the package they are testing, but should otherwise be avoided.) For instance, the buffered reader type in the bufio package is called Reader, not BufReader, because users see it as bufio.Reader, which is a clear, concise name. Moreover, because imported entities are always addressed with their package name, bufio.Reader does not conflict with io.Reader. Similarly, the function to make new instances of ring.Ring— which is the definition of a constructor in Go—would normally be called NewRing, but since Ring is the only type exported by the package, and since the package is called ring, it's called just New, which clients of the package see as ring.New. Use the package structure to help you choose good names. 包的导入者可通过包名来引用其内容,因此包中的可导出名称可以此来避免冲突。 (请勿使 用 import . 记法,它可以简化必须在被测试包外运行的测试, 除此之外应尽量避免使用。) 例如,bufio 包中的缓存读取器类型叫做 Reader 而非 BufReader,因为用户将它看做 bufio.Reader,这是个清楚而简洁的名称。 此外,由于被导入的项总是通过它们的包名来确 定,因此 bufio.Reader 不会与 io.Reader 发生冲突。同样,用于创建 ring.Ring 的新实例的函 数(这就是 Go 中的构造函数)一般会称之为 NewRing,但由于 Ring 是该包所导出的唯一类 型,且该包也叫 ring,因此它可以只叫做 New,它跟在包的后面,就像 ring.New。使用包结 构可以帮助你选择好的名称。 Another short example is once.Do; once.Do(setup) reads well and would not be improved by writing once.DoOrWaitUntilDone(setup). Long names don't automatically make things more readable. A helpful doc comment can often be more valuable than an extra long name. 另一个简短的例子是 once.Do,once.Do(setup) 表述足够清晰, 使用 once.DoOrWaitUntilDone(setup) 完全就是画蛇添足。 长命名并不会使其更具可读性。一份有 用的说明文档通常比额外的长名更有价值。 Getters 17
18 .命名 获取器 Go doesn't provide automatic support for getters and setters. There's nothing wrong with providing getters and setters yourself, and it's often appropriate to do so, but it's neither idiomatic nor necessary to put Get into the getter's name. If you have a field called owner (lower case, unexported), the getter method should be called Owner (upper case, exported), not GetOwner. The use of upper-case names for export provides the hook to discriminate the field from the method. A setter function, if needed, will likely be called SetOwner. Both names read well in practice: Go 并不对获取器(getter)和设置器(setter)提供自动支持。 你应当自己提供获取器和设 置器,通常很值得这样做,但若要将 Get 放到获取器的名字中,既不符合习惯,也没有必 要。若你有个名为 owner (小写,未导出)的字段,其获取器应当名为 Owner(大写,可导 出)而非 GetOwner。大写字母即为可导出的这种规定为区分方法和字段提供了便利。 若要 提供设置器方法,SetOwner 是个不错的选择。两个命名看起来都很合理: owner := obj.Owner() if owner != user { obj.SetOwner(user) } Interface names 接口名 By convention, one-method interfaces are named by the method name plus an -er suffix or similar modification to construct an agent noun: Reader, Writer, Formatter, CloseNotifier etc. 按照约定,只包含一个方法的接口应当以该方法的名称加上 - er 后缀来命名,如 Reader、 Writer、 Formatter、CloseNotifier 等。 There are a number of such names and it's productive to honor them and the function names they capture. Read, Write, Close, Flush, String and so on have canonical signatures and meanings. To avoid confusion, don't give your method one of those names unless it has the same signature and meaning. Conversely, if your type implements a method with the same meaning as a method on a well-known type, give it the same name and signature; call your string-converter method String not ToString. 诸如此类的命名有很多,遵循它们及其代表的函数名会让事情变得简单。 Read、Write、 Close、Flush、 String 等都具有典型的签名和意义。为避免冲突,请不要用这些名称为你的 方法命名, 除非你明确知道它们的签名和意义相同。反之,若你的类型实现了的方法, 与一 个众所周知的类型的方法拥有相同的含义,那就使用相同的命名。 请将字符串转换方法命名 为 String 而非 ToString。 18
19 .命名 MixedCaps 驼峰记法 Finally, the convention in Go is to use MixedCaps or mixedCaps rather than underscores to write multiword names. 最后,Go 中约定使用驼峰记法 MixedCaps 或 mixedCaps。 19
20 .分号 Semicolons 分号 Like C, Go's formal grammar uses semicolons to terminate statements, but unlike in C, those semicolons do not appear in the source. Instead the lexer uses a simple rule to insert semicolons automatically as it scans, so the input text is mostly free of them. 和 C 一样,Go 的正式语法使用分号来结束语句;和 C 不同的是,这些分号并不在源码中出 现。 取而代之,词法分析器会使用一条简单的规则来自动插入分号,因此因此源码中基本就 不用分号了。 The rule is this. If the last token before a newline is an identifier (which includes words like int and float64), a basic literal such as a number or string constant, or one of the tokens 规则是这样的:若在新行前的最后一个标记为标识符(包括 int 和 float64 这类的单词)、数 值或字符串常量之类的基本字面或以下标记之一 break continue fallthrough return ++ -- ) } the lexer always inserts a semicolon after the token. This could be summarized as, “if the newline comes after a token that could end a statement, insert a semicolon”. 则词法分析将始终在该标记后面插入分号。这点可以概括为: “如果新行前的标记为语句的末 尾,则插入分号”。 A semicolon can also be omitted immediately before a closing brace, so a statement such as 分号也可在闭括号之前直接省略,因此像 go func() { for { dst <- <-src } }() needs no semicolons. Idiomatic Go programs have semicolons only in places such as for loop clauses, to separate the initializer, condition, and continuation elements. They are also necessary to separate multiple statements on a line, should you write code that way. 这样的语句无需分号。通常Go程序只在诸如 for 循环子句这样的地方使用分号, 以此来将初 始化器、条件及增量元素分开。如果你在一行中写多个语句,也需要用分号隔开。 20
21 .分号 One consequence of the semicolon insertion rules is that you cannot put the opening brace of a control structure (if, for, switch, or select) on the next line. If you do, a semicolon will be inserted before the brace, which could cause unwanted effects. Write them like this 警告:无论如何,你都不应将一个控制结构(if、for、switch 或 select)的左大括号放在下一 行。如果这样做,就会在大括号前面插入一个分号,这可能引起不需要的效果。 你应该这样 写 if i < f() { g() } not like this 而不是这样 if i < f() // wrong! { // wrong! g() } if i < f() // 错! { // 错! g() } 21
22 .控制结构 Control structures 控制结构 The control structures of Go are related to those of C but differ in important ways. There is no do or while loop, only a slightly generalized for; switch is more flexible; if and switch accept an optional initialization statement like that of for; break and continue statements take an optional label to identify what to break or continue; and there are new control structures including a type switch and a multiway communications multiplexer, select. The syntax is also slightly different: there are no parentheses and the bodies must always be brace- delimited. Go 中的结构控制与 C 有许多相似之处,但其不同之处才是独到之处。 Go 不再使用 do 或 while 循环,只有一个更通用的 for;switch 要更灵活一点;if 和 switch 像 for 一样可接受可选 的初始化语句; 此外,还有一个包含类型选择和多路通信复用器的新控制结构:select。 其 语法也有些许不同:没有圆括号,而其主体必须始终使用大括号括住。 If In Go a simple if looks like this: 在 Go 中,一个简单的 if 语句看起来像这样: if x > 0 { return y } Mandatory braces encourage writing simple if statements on multiple lines. It's good style to do so anyway, especially when the body contains a control statement such as a return or break. 强制的大括号促使你将简单的 if 语句分成多行。特别是在主体中包含 return 或 break 等控制 语句时,这种编码风格的好处一比便知。 Since if and switch accept an initialization statement, it's common to see one used to set up a local variable. 由于 if 和 switch 可接受初始化语句, 因此用它们来设置局部变量十分常见。 22
23 .控制结构 if err := file.Chmod(0664); err != nil { log.Print(err) return err } In the Go libraries, you'll find that when an if statement doesn't flow into the next statement— that is, the body ends in break, continue, goto, or return—the unnecessary else is omitted. 在 Go 的库中,你会发现若 if 语句不会执行到下一条语句时,亦即其执行体 以 break、 continue、goto 或 return 结束时,不必要的 else 会被省略。 f, err := os.Open(name) if err != nil { return err } codeUsing(f) This is an example of a common situation where code must guard against a sequence of error conditions. The code reads well if the successful flow of control runs down the page, eliminating error cases as they arise. Since error cases tend to end in return statements, the resulting code needs no else statements. 下例是一种常见的情况,代码必须防范一系列的错误条件。若控制流成功继续, 则说明程序 已排除错误。由于出错时将以 return 结束, 之后的代码也就无需 else 了。 f, err := os.Open(name) if err != nil { return err } d, err := f.Stat() if err != nil { f.Close() return err } codeUsing(f, d) Redeclaration and reassignment 重新声明与再次赋值 An aside: The last example in the previous section demonstrates a detail of how the := short declaration form works. The declaration that calls os.Open reads, 题外话:上一节中最后一个示例展示了短声明 := 如何使用。 调用了 os.Open 的声明为 23
24 .控制结构 f, err := os.Open(name) This statement declares two variables, f and err. A few lines later, the call to f.Stat reads, 该语句声明了两个变量 f 和 err。在几行之后,又通过 d, err := f.Stat() which looks as if it declares d and err. Notice, though, that err appears in both statements. This duplication is legal: err is declared by the first statement, but only re-assigned in the second. This means that the call to f.Stat uses the existing err variable declared above, and just gives it a new value. 调用了 f.Stat。它看起来似乎是声明了 d 和 err。 注意,尽管两个语句中都出现了 err,但这 种重复仍然是合法的:err 在第一条语句中被声明,但在第二条语句中只是被再次赋值罢了。 也就是说,调用 f.Stat 使用的是前面已经声明的 err,它只是被重新赋值了而已。 In a := declaration a variable v may appear even if it has already been declared, provided: 在满足下列条件时,已被声明的变量 v 可出现在:= 声明中: this declaration is in the same scope as the existing declaration of v (if v is already declared in an outer scope, the declaration will create a new variable §), the corresponding value in the initialization is assignable to v, and there is at least one other variable in the declaration that is being declared anew. 本次声明与已声明的 v 处于同一作用域中(若 v 已在外层作用域中声明过,则此次声明 会创建一个新的变量 §), 在初始化中与其类型相应的值才能赋予 v,且 在此次声明中至少另有一个变量是新声明的。 This unusual property is pure pragmatism, making it easy to use a single err value, for example, in a long if-else chain. You'll see it used often. 这个特性简直就是纯粹的实用主义体现,它使得我们可以很方面地只使用一个 err 值,例如, 在一个相当长的 if-else 语句链中, 你会发现它用得很频繁。 § It's worth noting here that in Go the scope of function parameters and return values is the same as the function body, even though they appear lexically outside the braces that enclose the body. § 值得一提的是,即便 Go 中的函数形参和返回值在词法上处于大括号之外, 但它们的作用 域和该函数体仍然相同。 24
25 .控制结构 For The Go for loop is similar to—but not the same as—C's. It unifies for and while and there is no do-while. There are three forms, only one of which has semicolons. Go 的 for 循环类似于 C,但却不尽相同。它统一了 for 和 while,不再有 do-while 了。它有三 种形式,但只有一种需要分号。 // Like a C for for init; condition; post { } // Like a C while for condition { } // Like a C for(;;) for { } // 如同 C 的 for 循环 for init; condition; post { } // 如同 C 的 while 循环 for condition { } // 如同 C 的 for(;;) 循环 for { } Short declarations make it easy to declare the index variable right in the loop. 简短声明能让我们更容易在循环中声明下标变量: sum := 0 for i := 0; i < 10; i++ { sum += i } If you're looping over an array, slice, string, or map, or reading from a channel, a range clause can manage the loop. 若你想遍历数组、切片、字符串或者映射,或从信道中读取消息, range 子句能够帮你轻松 实现循环。 for key, value := range oldMap { newMap[key] = value } 25
26 .控制结构 If you only need the first item in the range (the key or index), drop the second: 若你只需要该遍历中的第一个项(键或下标),去掉第二个就行了: for key := range m { if key.expired() { delete(m, key) } } If you only need the second item in the range (the value), use the blank identifier, an underscore, to discard the first: 若你只需要该遍历中的第二个项(值),请使用空白标识符,即下划线来丢弃第一个值: sum := 0 for _, value := range array { sum += value } The blank identifier has many uses, as described in a later section. 空白标识符还有多种用法,它会在后面的小节中描述。 For strings, the range does more work for you, breaking out individual Unicode code points by parsing the UTF-8. Erroneous encodings consume one byte and produce the replacement rune U+FFFD. (The name (with associated builtin type) rune is Go terminology for a single Unicode code point. See the language specification for details.) The loop 对于字符串,range 能够提供更多便利。它能通过解析 UTF-8, 将每个独立的 Unicode 码点 分离出来。错误的编码将占用一个字节,并以符文 U+FFFD 来代替。 (名称 “符文” 和内建类 型 rune 是 Go 对单个 Unicode 码点的成称谓。 详情见语言规范)。循环 for pos, char := range "日本 \ x80 語" { // \x80 is an illegal UTF-8 encoding fmt.Printf("character %#U starts at byte position %d\n", char, pos) } prints character U+65E5 '日' starts at byte position 0 character U+672C '本' starts at byte position 3 character U+FFFD '�' starts at byte position 6 character U+8A9E '語' starts at byte position 7 26
27 .控制结构 for pos, char := range "日本\x80語" { // \x80 是个非法的UTF-8编码 fmt.Printf("字符 %#U 始于字节位置 %d\n", char, pos) } 将打印 字符 U+65E5 '日' 始于字节位置 0 字符 U+672C '本' 始于字节位置 3 字符 U+FFFD '�' 始于字节位置 6 字符 U+8A9E '語' 始于字节位置 7 Finally, Go has no comma operator and ++ and -- are statements not expressions. Thus if you want to run multiple variables in a for you should use parallel assignment (although that precludes ++ and --). 最后,Go 没有逗号操作符,而 ++ 和 -- 为语句而非表达式。 因此,若你想要在 for 中使用多 个变量,应采用平行赋值的方式 (因为它会拒绝 ++ 和 --). // Reverse a for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 { a[i], a[j] = a[j], a[i] } // 反转 a for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 { a[i], a[j] = a[j], a[i] } Switch Go's switch is more general than C's. The expressions need not be constants or even integers, the cases are evaluated top to bottom until a match is found, and if the switch has no expression it switches on true. It's therefore possible—and idiomatic—to write an if-else- if-else chain as a switch. Go 的 switch 比 C 的更通用。其表达式无需为常量或整数,case 语句会自上而下逐一进行求 值直到匹配为止。若 switch 后面没有表达式,它将匹配 true,因此,我们可以将 if-else-if- else 链写成一个 switch,这也更符合 Go 的风格。 27
28 .控制结构 func unhex(c byte) byte { switch { case '0' <= c && c <= '9': return c - '0' case 'a' <= c && c <= 'f': return c - 'a' + 10 case 'A' <= c && c <= 'F': return c - 'A' + 10 } return 0 } There is no automatic fall through, but cases can be presented in comma-separated lists. switch 并不会自动下溯,但 case 可通过逗号分隔来列举相同的处理条件。 func shouldEscape(c byte) bool { switch c { case ' ', '?', '&', '=', '#', '+', '%': return true } return false } Although they are not nearly as common in Go as some other C-like languages, break statements can be used to terminate a switch early. Sometimes, though, it's necessary to break out of a surrounding loop, not the switch, and in Go that can be accomplished by putting a label on the loop and"breaking" to that label. This example shows both uses. 尽管它们在 Go 中的用法和其它类 C 语言差不多,但 break 语句可以使 switch 提前终止。不 仅是 switch, 有时候也必须打破层层的循环。在 Go 中,我们只需将标签放置到循环外,然 后 “蹦” 到那里即可。下面的例子展示了二者的用法。 28
29 .控制结构 Loop: for n := 0; n < len(src); n += size { switch { case src[n] < sizeOne: if validateOnly { break } size = 1 update(src[n]) case src[n] < sizeTwo: if n+1 >= len(src) { err = errShortInput break Loop } if validateOnly { break } size = 2 update(src[n] + src[n+1]<<shift) } } Of course, the continue statement also accepts an optional label but it applies only to loops. 当然,continue 语句也能接受一个可选的标签,不过它只能在循环中使用。 To close this section, here's a comparison routine for byte slices that uses two switch statements: // Compare returns an integer comparing the two byte slices, // lexicographically. // The result will be 0 if a == b, -1 if a < b, and +1 if a > b func Compare(a, b []byte) int { for i := 0; i < len(a) && i < len(b); i++ { switch { case a[i] > b[i]: return 1 case a[i] < b[i]: return -1 } } switch { case len(a) > len(b): return 1 case len(a) < len(b): return -1 } return 0 } 29