Golang 常见规范
一、代码规范
1.1 包引入(import package)
import (
"io"
"net"
"net/http"
conf "xxxxxx/Conf"
udp "xxxxxx/Udp"
"github.com/gin-gonic/gin"
)
1.2 变量、函数
var (
boolValue []bool
intValue []int
uint32Value []uint32
float32Value []float32
float64Value []float64
)
const(
Length = 1
Name = "a"
)
func TestInit(a, b bool) error {
boolValue := true
BoolValue = make([]bool, 0, 10)
BoolValue = append(BoolValue, []bool{a, b, boolValue, testBool()}...)
return nil
}
func testBool() bool {
return true
}
1.3 结构体定义 struct
type ClientTest struct {
mu sync.Mutex
ConnRemotePort int
ConnType string
HeartbeatCtr int64
Interval uint32
Conn *net.UDPConn
Timer *time.Timer
WsMessageChan chan []byte
RegisterMessageChan map[uint]*RegisterMessageChan
}
1.4 文件名
// 文件名称可以用下划线区分,尽量避免
// 如果采用下划线命名,注意避免和下面特定用法冲突
1. 测试单元命名 _test.go
client_test.go
2. 系统相关文件
_386.go、_amd64.go、_arm.go、_arm64.go、_android.go、_darwin.go、
_dragonfly.go、_freebsd.go、_linux.go、_nacl.go、_netbsd.go、
_openbsd.go、_plan9.go、_solaris.go、_windows.go、_android_386.go、
_android_amd64.go、_android_arm.go、_android_arm64.go、_darwin_386.go、
_darwin_amd64.go、_darwin_arm.go、_darwin_arm64.go、_dragonfly_amd64.go、
_freebsd_386.go、_freebsd_amd64.go、_freebsd_arm.go、_linux_386.go、
_linux_amd64.go、_linux_arm.go、_linux_arm64.go、_linux_mips64.go、
_linux_mips64le.go、_linux_ppc64.go、_linux_ppc64le.go、_linux_s390x.go、
_nacl_386.go、_nacl_amd64p32.go、_nacl_arm.go、_netbsd_386.go、
_netbsd_amd64.go、_netbsd_arm.go、_openbsd_386.go、_openbsd_amd64.go、
_openbsd_arm.go、_plan9_386.go、_plan9_amd64.go、_plan9_arm.go、
_solaris_amd64.go、_windows_386.go、_windows_amd64.go
二、注释规范
2.1 包注释
package io
2.2 结构体注释(同 接口注释)
type ClientTest struct {
Mu sync.Mutex
ConnRemotePort int
ConnType string
HeartbeatCtr int64
Interval uint32
Conn *net.UDPConn
Timer *time.Timer
WsMessageChan chan []byte
RegisterMessageChan map[uint]*RegisterMessageChan
}
2.3 函数注释
func DeCodeByProto(port int, bytes []byte) (proto.Message, error) {
header := bytes[:4]
length := bytesToUint16(header[1:3])
msgTypeCode := bytesToUint8(header[3:4])
msgBody := bytes[4:length+4]
switch(port) {
case 9000, 9010, 9020:
return byteToProtoMsgWithVCI(conf.VCIMessage[msgTypeCode], msgBody)
case 9030, 9040:
return byteToProtoMsgWithPMM(conf.VCIMessage[msgTypeCode], msgBody)
case 9030, 9050:
return byteToProtoMsgWithOHP(conf.VCIMessage[msgTypeCode], msgBody)
}
return nil, errors.New("don't use bed prot")
}