《Go语言精进之路》第二、三章部分内容学习记录笔记。
Golang开发中,可遵守简单且一致的命名原则,力求命名精简、易懂和一致。
shopservice、utils、logs、tcc、logconfigs、encoding [good]
不建议以复合词形式来命名:
shop_service、log_configs [bad]
users []*User [good]
userList []*User [bad]
使用驼峰形式来声明变量,而不是下划线形式:
var userInfo *User [good]
var user_info *User [bad]
const (
TaskTypeA = "A" [good]
Task_Type_B = "B" [bad]
)
对于专有名词或特定常量,可使用全大写形式:
const (
SIGABRT = Singnal(0x6) [good]
SIGALRM = Singnal(0xe) [good]
sig_abrt = Singnal(0x6) [bad]
)
type Writer interface { [good]
}
type Write interface { [bad]
}
for i := 0, i < len(s); i++ { [good]
v := s[i]
...
}
for index := 0, index < len(s); index++ { [bad]
value := s[index]
...
}
var ( [good]
a = int32(1)
f = float32(3.14)
)
var ( [bad]
a int32 = 1
f float32 = 3.14
)
var a int32
var f float32
var ErrNoUserInfo = errors.New("用户信息不存在")
func GetUserInfo(name string) (*User, error) {
...
return nil, ErrNoUserInfo
}
func GetUserInfo(name string)(*User, error) {
// 前置声明
var user *User
if user, err := getUserDB(name); err != nil {
return nil, err
}
return user, nil
}
[good]
taskType := int32(1)
s := []byte("hlelo")
[bad]
var taskType int32 = 1
var s []byte = []byte("hello")
[good]
func Do(userName string) (*User, error){
var u User
if u, ok := userMap[userName]; !ok {
return nil, ErrNoUser
}
for _, s := range u.Shops {
handleShop(s)
...
}
}
[bad]
func Do(userName string) (*User, error){
var user User
if user, existUser := userMap[userName]; !existUser {
return nil, ErrNoUser
}
for _, userShop := range user.Shops {
handleShop(userShop)
...
}
}
const ( [good]
a = 1
f = float64(3.14)
)
const ( [bad]
a int32 = 1
f float64 = 3.14
)
[good]
const (
_ = iota // 0
A
B
C
)
[bad]
const (
A = 1
B = 2
C = 3
)
var list []int // 该切片声明为零值
list = append(list, 1) // 依然生效,会自动初始化list
var mu sync.Mutex // 该mutex声明为零值
mu.Lock()
mu.Unlock()
type Person struct {
Name string
Age int
Child *Person
}
func main() {
var p Person // 声明结构体后,自动为其内部各字段赋零值
p.Age = 1
p.Name = "test"
p.Child = &Person{}
}
func (p *Person) GetPersonName() string {
if p == nil {
return ""
}
return p.Name
}
func main() {
var p *Person // 声明零值指针
name := p.GetPersonName() // 零值指针调用方法
fmt.Println(name) // 输出,表明零值指针调用方法可行
}