Formatting
用gofmt
對源文件格式化(用go fmt
對package
格式化)
Commentary
支持/* */
風(fēng)格的塊注釋和//
風(fēng)格的行注釋嫁艇。文檔注釋開頭最好用函數(shù)名(便于grep
時找到函數(shù)名)煮岁“只疲縮進的文本采用等寬字體猿挚,適用于代碼片段烁兰。
Names
導(dǎo)出符號需要將其首字母大寫。
- Package names
包名是應(yīng)當(dāng)簡短、具體、形象的聘萨,通常是小寫和單個詞,因此不需要下劃線和混合大小寫童太。因為需要包名做前綴米辐,所以包內(nèi)導(dǎo)出的名字可以簡短些,比如用bufio.Reader
代替bufio.BufReader
书释。 - Getters
Get
方法的名字里不需要加Get
翘贮。 - Interface names
單個方法的接口用帶-er
的后綴或者類似的方式命名成代理人名詞,比如Reader
,Writer
,Formatter
,CloseNotifier
等爆惧。 - MixedCaps
用MixedCaps
或mixedCaps
而不是下劃線狸页。
Semicolons
像C
一樣Go
也用分號來分隔語句,但它會根據(jù)規(guī)則(在終結(jié)語句的token
和新行之間)自動插入分號。
Control structures
復(fù)用已聲明的變量的實用規(guī)則芍耘,比如重用下面的err
變量
f, err := os.Open(name) // 聲明f和err
d, err := f.Stat() // 聲明d址遇,重賦值err
Switch
語句支持逗號分隔的列表case ' ', '?', '&', '=', '#', '+', '%':
Type switch
變量自動擁有每個子句對應(yīng)的類型
var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T", t) // %T prints whatever type t has
case bool:
fmt.Printf("boolean %t\n", t) // t has type bool
case int:
fmt.Printf("integer %d\n", t) // t has type int
case *bool:
fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}
Functions
- Multiple return values
- Named result parameters
- Defer
調(diào)用參數(shù)在defer
執(zhí)行時被求值,而非函數(shù)調(diào)用時斋竞。并且被延遲的函數(shù)按照LIFO
的順序執(zhí)行倔约。
Data
- Allocation with new
new
用零值初始化所有類型。 - Constructors and composite literals
- Allocation with make
- Arrays
- Slices
- Two-dimensional slices
- Maps
可以用作key
的包括integers
,floating point and complex numbers
,strings
,pointers
,interfaces (as long as the dynamic type supports equality)
,structs and arrays
等定義了相等性的類型坝初。
// Create a timezone
var timeZone = map[string]int{
"UTC": 0 * 60 * 60,
"EST": -5 * 60 * 60,
"CST": -6 * 60 * 60,
"MST": -7 * 60 * 60,
"PST": -8 * 60 * 60,
}
offset := timeZone["EST"] // Get value
seconds, ok := timeZone[tz] // Get value and present
_, present := timeZone[tz] // Get present
delete(timeZone, "PDT") // Delete key
- Printing
在格式化字符串中根據(jù)數(shù)據(jù)類型而不是flag
來決定有無符號和位數(shù)浸剩。 -
%v (for "value")
用來指定任何值的默認(rèn)格式,跟Print
和Println
的輸出一樣鳄袍。 -
%+v
在輸出結(jié)構(gòu)體時绢要,還附帶上每個域的名字。 -
%#v
輸出完整的Go
語法畦木。 -
%q
應(yīng)用到string
和[]byte
類型上輸出帶引號的字符串。%#q
則盡可能用反引號砸泛。 -
%x
應(yīng)用到strings
,byte arrays
,byte slices
,integers
生成長長的十六進制字符串十籍。% x
(有個空格)在字節(jié)間加上空格。 -
%T
用來輸出值的類型唇礁。
可變參數(shù)使用...
來指定
// Println prints to the standard logger in the manner of fmt.Println.
func Println(v ...interface{}) {
std.Output(2, fmt.Sprintln(v...)) // Output takes parameters (int, string)
}
// We write ... after v in the nested call to Sprintln to tell the compiler to treat v
as a list of arguments; otherwise it would just pass v as a single slice argument.
- Append