[翻譯] effective go 之 Formatting Commentary

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.