Go编码规范

2023-08-19  本文已影响0人  无心Y

命名规范

文件名

base_test.go

包命名

package main

package utils

结构体

type User struct {
    Name   string
    Age    uint32
    Gender uint8
}

接口名

interface Reader {
    Read(content []byte) (n int, err error)
}

interface ReadWriter {
    Read(content []byte) (n int, err error)
    Write(content []byte) (n int, err error)
}

type Car interface {
    Start([]byte)
    Stop() error
    Recover()
}

函数名

type Pen struct{
    Length  float64
    owner   string
}


(p *Pen) func Owner() string {
    return p.owner
}

(p *Pen) func SetOwner(owner string) {
    p.owner = owner
}

func HasPrefix(name string, prefixes []string) bool { ... }
func IsEntry(name string, entries []string) bool { ... }
func CanManage(name string) bool { ... }
func AllowGitHook() bool { ... }

常量名


const APP_VERSION = "1.0"

type Protocol string

const (
    HTTP  Protocol = "http"
    HTTPS Protocol = "https"
)

type PullRequestStatus int

const (
    PULL_REQUEST_STATUS_CONFLICT PullRequestStatus = iota
    PULL_REQUEST_STATUS_CHECKING
    PULL_REQUEST_STATUS_MERGEABLE
)

变量名

var (
    ProjectName  string
    ProjectOwner string
)

projectName  := "venus"
projectOwner := "loda"

注释规范

注释风格

包注释

// util 包含一些公用的函数
// Author: loda
// Date: 20210723

package util

结构体(接口)注释

// User , 用户对象,定义了用户的基础信息
type User struct{
    Username  string // 用户名
    Email     string // 邮箱
}

函数(方法)注释

// @Title NewtAttrModel 
// @Description 属性数据层操作类的工厂方法
// @Author loda
// @Param  ctx  上下文信息
// @Return 属性操作类指针
func NewAttrModel(ctx *common.Context) *AttrModel {
}

代码逻辑注释

Bug注释

// BUG(astaxie):This divides by zero. 
var i float = 1/0

代码风格

缩进和换行

控制结构

result := query()

if err := check(result); err != nil {
    return err
}


for i:=0; i++; i<10 {
    // do sth
}

import fmt

for pos, str := range "hello" {
    fmt.Printf("%q: %d\n", str, pos)
}

// 遍历 array, slice, map, chan, string
for k, v := range mapA {
    // do sth
}

func Factory(name string, value interface{}) interface{} {
    var object interface{}

    switch name {
    case "A1", "A2":
        object = NewA()
    case "B":
        object = newB()
        if value == nil {
            break
            }
        object.SetValue(value)
    }

    return object
}

func ErrorWrap(e interface{}) *TraceableError {
    var message string

    switch e := e.(type) {
    case TraceableError:
        return &e
    case *TraceableError:
        return e
    case error:
        message = e.Error()
    default:
        message = fmt.Sprintf("%v", e)
    }
    return ErrorNew(message, 2)
}

package main

import (
    "fmt"
)

func main() {
Loop:
    for index := 1; index < 10; index++ {
        switch index % 5 {
        case 1:
            break 
        case 0:
            break Loop
        default:
            fmt.Printf("%v\n", index)
        } 
    }
}

结构体和接口

type MyStruct struct {
    Value int
}

type MyStruct2 struct {
    MyStruct
    ID int 
}

p1 := new (MyStruct) // type *SyncedBuffer
p2 := &MyStruct{}   // type *SyncedBuffer

s1 := MyStruct{
    Value: 0, 
}

s2 := MyStruct2{
    ID: 0,
    MyStruct1: MyStruct1 {
        Value: 1, 
    },
}

method receiver

defer

chan


ch := make(chan int 1)

func handle(readCh <-chan int, writeCh chan<- int) {
    go func() {
        v := <-readCh
        writeCh <- 2 * v
    }()
}

gorouting

package main

import (
    "sync"
)

type singleton struct {}

var instance *singleton

var once sync.Once

func GetInstance() *singleton {
    once.Do(func() {
        instance = &singleton{}
    })
    return instance
}

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup

    wg.Add(1)

    go func() {
            fmt.Printf("hello ")
            wg.Done()
        }()

    wg.Wait()
    fmt.Printf("world\n")
}

package main

import (
    "fmt"
    "sync"
    "sync/atomic"
)

func main() {
    var value int64
    var wg sync.WaitGroup

    wg.Add(2)

    fun := func(count int) {
        for index := 0; index < count; index++ {
            atomic.AddInt64(&value, 1)
        }
        wg.Done()
    }

    go fun(100)
    go fun(100)

    wg.Wait()
    fmt.Printf("%v\n", value)
}

import规范

import (
    "encoding/json"  //标准包
    "strings"

    "myproject/models"
    "myproject/controller"   //内部包
    "myproject/utils"

    "github.com/astaxie/beego"   //第三方包
    "github.com/go-sql-driver/mysql"
) 

错误处理

// 错误写法
if err != nil {
    // error handling
} else {
    // normal code
}

// 正确写法
if err != nil {
    // error handling
    return // or continue, etc.
}
// normal code

参数传递

单元测试

上一篇下一篇

猜你喜欢

热点阅读