Go 若干技巧

此文來自 http://denvergophers.com/2013-09/tips-and-tricks.slide ###本文主要涉及到: 1. formatting 技巧 2. 異常處理技巧 3. 函數返回值的一致性 ###代碼資源: https://denvergophers.com/tips-and-tricks http://golang.org/pkg/fmt http://godoc.org/code.google.com/p/go.tools/present ## fmt包 使用以下格式導入: import "fmt" 普通佔位符: %v 相應值的默認格式 %+v 在打印結構體時,會添加字段名 %#v 相應值的Go語法表示 %T 相應值的類型的Go語法表示 %% 字面上的百分號,並不是值的佔位符 ### fmt通常用法 - 簡單字符串 var foo string = "This is a simple string" fmt.Printf("%v\n", foo) fmt.Printf("%T\n", foo) ### fmt通常用法 - 結構(struct) 首先,準備好結構 type ( Customer struct { Name string Street []string City string State string Zip string } Item struct { Id int Name string Quantity int } Items []Item Order struct { Id int Customer Customer Items Items } ) 關於結構格式化的一些技巧: // 這是我調試時的默認格式 fmt.Printf("%+v\n\n", order) // 當我須要知道這個變量的有關結構時我會用這種方法 fmt.Printf("%#v\n\n", order) // 我不多使用這些 fmt.Printf("%v\n\n", order) fmt.Printf("%s\n\n", order) fmt.Printf("%T\n", order) ### fmt - 使用errors.New()生成Errors 這是我最不喜歡看到的建立異常的方式: import ( "errors" "fmt" "log" ) func main() { if err := iDunBlowedUp(-100); err != nil { err = errors.New(fmt.Sprintf("Something went wrong: %s\n", err)) log.Println(err) return } fmt.Printf("Success!") } func iDunBlowedUp(val int) error { return errors.New(fmt.Sprintf("invalid value %d", val)) } 我是這麼建立異常的: import ( "fmt" "log" ) func main() { if err := iDunBlowedUp(-100); err != nil { err = fmt.Errorf("Something went wrong: %s\n", err) log.Println(err) return } fmt.Printf("Success!") } func iDunBlowedUp(val int) error { return fmt.Errorf("invalid value %d", val) } ### fmt - 函數返回值的一致性 壞習慣: func someFunction(val int) (ok bool, err error) { if val == 0 { return false, nil } if val < 0 { return false, fmt.Errorf("value can't be negative %d", val) } ok = true return } 好習慣: func someFunction(val int) (bool, error) { if val == 0 { return false, nil } if val < 0 { return false, fmt.Errorf("value can't be negative %d", val) } return true, nil } 更好的方式(在我看來): func someFunction(val int) (ok bool, err error) { if val == 0 { return } if val < 0 { err = fmt.Errorf("value can't be negative %d", val) return } ok = true return } ## 參考 http://golang.org/ https://denvergophers.com/tips-and-tricks http://golang.org/pkg/fmt http://godoc.org/code.google.com/p/go.tools/present ## 做者相關 https://github.com/DenverGophers https://twitter.com/DenverGophers https://plus.google.com/u/0/communities/104822260820066412402
相關文章
相關標籤/搜索