Statistics
19
Views
2
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-05-04

Authorit-ebooks

No description

Tags
No tags
Publisher: it-ebooks
Publish Year: 2016
Language: 中文
File Format: PDF
File Size: 1.0 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
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 1.17 Table of Contents 前言 引言 格式化 注释 命名 分号 控制结构 函数 数据 初始化 方法 接口和其他类型 空白标识符 内嵌 并发 错误 一个Web服务器 2
《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 语言的入门必读教程,值得每位初学者好好阅读一遍,编辑成书,方 便阅读交流。 当前完成章节(全部完成): 前言 3
1. 前言 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
Read on Gitbook Fork on GitHub 请顺手点一下 STAR ,或者留言讨论,这是对我最大的鼓励! 下载 为了让大家更方便阅读,在此提供 网易蜂巢对象存储 的下载地址: [x] PDF格式 [x] EPUB格式 License 除特别注明外, 本页内容均采用知识共享 - 署名(CC-BY)3.0 协议授权,代码采用 BSD 协 议 授权。 前言 5
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
Go 包的源码 不仅是核心库,同时也是学习如何使用 Go 语言的示例源码。 此外,其中的一 些包还包含了可工作的,独立的可执行示例,你可以直接在 golang.org 网站上运行它们,比 如 这个例子 (单击文字 “示例” 来展开它)。如果你有任何关于某些问题如何解决,或某些东 西如何实现的疑问, 也可以从中获取相关的答案、思路以及后台实现。 引言 7
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
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
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
/* 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
// 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
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
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
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
导入时所需的唯一默认名称, 它并不需要在所有源码中保持唯一,即便在少数发生冲突的情 况下, 也可为导入的包选择一个别名来局部使用。 无论如何,通过文件名来判定使用的包, 都是不会产生混淆的。 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
获取器 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
MixedCaps 驼峰记法 Finally, the convention in Go is to use MixedCaps or mixedCaps rather than underscores to write multiword names. 最后,Go 中约定使用驼峰记法 MixedCaps 或 mixedCaps 而非下划线的方式来对多单词名称 进行命名。 命名 19
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