[翻译] effective go 之 Formatting Commentary

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这个工具可以规范缩进 垂直对齐 如果有必要的话 也会重新整理注释的格式 

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

下面这个例子 你大可不必把时间浪费在结构体字段对齐的问题上 

type T struct {
    name string // name of the object
    value int // its value
}

gofmt will line up the columns:

gofmt可以帮你解决这个问题 列对齐:

type T struct {
    name    string // name of the object
    value   int    // its value
}

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 lengthGo 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.ParenthesesGo needs fewer parentheses: control structures (if, for, switch) do not have parentheses in their syntax. Also, the operator precedence hierarchy is shorter and clearer, so

使用Tab来缩进 gofmt默认使用tab 如果没有必要的话 还是不要使用空格来做缩进(这个不太同意 vim写python习惯了 都是用空格来缩进 遇到过有的示例脚本 全是tab 那个程序简直没法改 要命)Go对行的长度没有显示 你不需要但是一行代码超过70个字符 现在大屏显示器上一行就可以容纳一两百个字符了吧 但是还是适当地断行比较好 换行可以添加一个额外的tab Go很少使用括号 if switch之类的条件判断不需要括号 操作符的优先级也更加简洁:

x<<8 + y<<16

means what the spacing implies.

上面所示的代码 可以按照空格分割出来的意思理解

Commentary 注释

Go provides C-style /* */ block comments and C++-style // line comments. Line comments are the norm; block comments appear mostly as package comments and are also useful 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.

Go中的注释和python中的doc string有点类似 那些和函数 包定义紧贴着的那些注释(中间没有使用空行隔开)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 thegodoc page and should set up the detailed documentation that follows.

每个包都需要加包注释 如果一个包有很多文件 那么主需要在一个文件中加上包注释就可以了

/*
    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

If the package is simple, the package comment can be brief.

注释的长短视情况而定

// Package path implements utility routines for
// manipulating slash-separated filename paths.

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. 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和gofmt一样可以帮你解决这些问题 注释就是简单的文字 不要使用HTML或者其它的标记

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.

紧靠在declaration 像函数定义之类的注释 会被当做是改declaration的文档 所有的可以被导出的名字都需要文档注释

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.

文档注释最好是完整的句子 这样可以更好地自动化展示出来 第一句应该是一句简短的概述 以被描述的名字开头 这个注释和GIT推荐的写注释的方式类似

// 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) {

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的声明语法允许一个var声明多个变量 一条文档注释可以带这样做(如下代码)由于整个声明的语句都写到了文档里 开头的那一句也就是起到抛砖引玉的作用

// 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 ')'")
    ...
)

Even for private names, grouping can also indicate relationships between items, such as the fact that a set of variables is protected by a mutex.

即使是私有的名字 把几个变量放在一起声明 也可以暗示它们之间的某种联系 下面这几个变量被Mutex给保护起来了

var (
    countLock   sync.Mutex
    inputCount  uint32
    outputCount uint32
    errorCount  uint32
)

你可能感兴趣的:(golang)