A Note of Effective Go (First Ha

2014-01-09  本文已影响0人  digiter

Formatting

gofmt对源文件格式化(用go fmtpackage格式化)

Commentary

支持/* */风格的块注释和//风格的行注释。文档注释开头最好用函数名(便于grep时找到函数名)。缩进的文本采用等宽字体,适用于代码片段。

Names

导出符号需要将其首字母大写。

Semicolons

C一样Go也用分号来分隔语句,但它会根据规则(在终结语句的token和新行之间)自动插入分号。

Control structures

复用已声明的变量的实用规则,比如重用下面的err变量

f, err := os.Open(name) // 声明f和err
d, err := f.Stat()      // 声明d,重赋值err

Switch语句支持逗号分隔的列表case ' ', '?', '&', '=', '#', '+', '%':

Type switch

变量自动拥有每个子句对应的类型

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

Data

// 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
// 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.
上一篇 下一篇

猜你喜欢

热点阅读