Go 若干技巧
此文來自 http://denvergophers.com/2013-09/tips-and-tricks.slide
###本文主要涉及到:
1. formatting 技巧
2. 異常處理技巧
3. 函數(shù)返回值的一致性
###代碼資源:
https://denvergophers.com/tips-and-tricks
http://golang.org/pkg/fmt
http://godoc.org/code.google.com/p/go.tools/present
## fmt包
使用如下格式導(dǎo)入:
import "fmt"
普通占位符:
%v 相應(yīng)值的默認(rèn)格式
%+v 在打印結(jié)構(gòu)體時(shí),會(huì)添加字段名
%#v 相應(yīng)值的Go語法表示
%T 相應(yīng)值的類型的Go語法表示
%% 字面上的百分號(hào),并非值的占位符
### fmt一般用法 - 簡(jiǎn)單字符串
var foo string = "This is a simple string"
fmt.Printf("%v\n", foo)
fmt.Printf("%T\n", foo)
### fmt一般用法 - 結(jié)構(gòu)(struct)
首先,準(zhǔn)備好結(jié)構(gòu)
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
}
)
關(guān)于結(jié)構(gòu)格式化的一些技巧:
// 這是我調(diào)試時(shí)的默認(rèn)格式
fmt.Printf("%+v\n\n", order)
// 當(dāng)我需要知道這個(gè)變量的有關(guān)結(jié)構(gòu)時(shí)我會(huì)用這種方法
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
這是我最不喜歡看到的創(chuàng)建異常的方式:
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))
}
我是這么創(chuàng)建異常的:
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 - 函數(shù)返回值的一致性
壞習(xí)慣:
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
}
好習(xí)慣:
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
## 作者相關(guān)
https://github.com/DenverGophers
https://twitter.com/DenverGophers
https://plus.google.com/u/0/communities/104822260820066412402
posted on 2013-09-29 12:11 黑暗伯爵 閱讀(1357) 評(píng)論(0) 收藏 舉報(bào)
浙公網(wǎng)安備 33010602011771號(hào)