go-style-guide

go style guide

Stars
6

Go(beta)

import

Don't
import ../config
Do
import github.com/voidint/gbb/config

return

Don't
func run() (n int, err error) {
	// ...
	return
}
Do
func run() (n int, err error) {
	// ...
	return n, err
}

uint

`intuintint```

Do
type Person struct{
	Age int
}
Don't
type Person struct{
	Age uint
}

slice

Don't
s := []string{} // 
Do
var s []string // 

:=

Don't
func saySomething() {
	var msg = getMsg()
	fmt.Println(msg)
}
Do

func saySomething() {
	msg := getMsg()
	fmt.Println(msg)
}

``

Don't
type Student struct{
	Name string
}

stu := Student{
	Name: "voidint",
}

func main(){
	fmt.Printf("student name: %s\n", stu.Name)
}
Do
type Student struct{
	name string
}

func NewStudent(name string) *Student{
	return &Student{name: name}
}

func (stu Student) Name() string{
	return stu.name
}

func main(){
	fmt.Printf("student name: %s\n", NewStudent("voidint").Name())
}

``

Don't
var	student_name string
const LOG_LEVEL = "info"
Do
var	studentName string
const LogLevel = "info"
Don't
var (
	Cpu string 
	Id int
)
Do
var (
	CPU string 
	id int
)
Don't
func add(X, Y int) (Z int) {
	return X + Y
}
Do
func add(x, y int) (z int) {
	return x + y
}

godoc

Don't
func SplitHostPort(hostport string) (string, string, error){
...
}
Do
func SplitHostPort(hostport string) (host, port string, err error){
...
}

codelf

package

Don't
package busyBox
Do
package busybox
Don't
package utils
Do
package util
Don't
package chubby

type ChubbyFile struct{
}
Do
package chubby

type File struct{
}

interface

er

Don't
type IRead interface{
}
Do
type Reader interface{
}

Don't
// service/network_service.go
package service
Do
// service/network.go
package service

error

error

_``errorerrorerror

Don't

Do
scores := map[string]int{
	"jim": 8,
	"jerry": 7,
	"tom": 3,
}

b,_ := json.Marshal(scores) // TODO 
fmt.Printf("%s", b)

error

Don't
var (
	ErrInvalidIP = errors.New("IP")
	ErrInvalidMacAddr = errors.New("Invalid mac address")
)
Do
var (
	ErrInvalidIP = errors.New("invalid ip")
	ErrInvalidMacAddr = errors.New("invalid mac address")
)
Don't
var (
	ErrInvalidIP = errors.New("invalid ip!")
)
Do
var (
	ErrInvalidIP = errors.New("invalid ip")
)

panicerror

error``panic

Don't
func (repo model.Repo) GetUserByName(name string)(user *model.User){
	if name == ""{
		panic("user name can't be empty")
	}
	...
}
Do
var ErrEmptyUserName = errors.New("user name can't be empty")

func (repo model.Repo) GetUserByName(name string)(user *model.User, err error){
	if name == ""{
		return nil, ErrEmptyUserName
	}
	...
}

`errorpanicMust```

Do
package regexp

// MustCompile is like Compile but panics if the expression cannot be parsed.
// It simplifies safe initialization of global variables holding compiled regular
// expressions.
func MustCompile(str string) *Regexp {
  	regexp, error := Compile(str)
  	if error != nil {
  		panic(`regexp: Compile(` + quote(str) + `): ` + error.Error())
  	}
  	return regexp
}

```panic`

Do
type Season int

const (
	Spring Season = iota
	Summer
	Fall
	Winter
)

func SeasonName(season Season) string {
	switch season {
	case Spring:
		return "Spring"
	case Summer:
		return "Summer"
	case Fall:
		return "Fall"
	case Winter:
		return "Winter"
	}
	panic("unreachable") 
}
  • error``panic``error

+``fmt.Sprintf``strings.Builder

Don't
func (stu Student) String() string {
	return stu.Num + " " + stu.Name + " " + stu.Age
}
Do
func (stu Student) String() string {
	return fmt.Sprintf("%s %s %d", stu.Num, stu.Name, stu.Age)
}

// OR

func (stu Student) String() string {
	var buf bytes.Buffer
	buf.WriteString(stu.Num)
	buf.WriteString(" ")
	buf.WriteString(stu.Name)
	buf.WriteString(" ")
	buf.WriteString(stu.Age)
	return buf.String()
}

receiver

receivermap,func,chan

receiverslice,

receiver,

receiver

receiver

``

Don't
err := file.Chmod(0664)
if err != nil {
    return err
}
Do
if err := file.Chmod(0664); err != nil {
    return err
}

return

Don't
func gender(female bool) (desc string){
	if female {
		return "female"
	} else {
		return "male"
	}
}
Do
func gender(female bool) (desc string){
	if female {
		return "female"
	}
	return "male"
}
Don't
func gender(female bool) (desc string){
	if female == true {
		return "female"
	}
	return "male"
}
Do
func gender(female bool) (desc string){
	if female{
		return "female"
	}
	return "male"
}

slice

Don't
type BigStruct struct{
	ID int
}

items := []BigStruct{
	{ID: 0},
	{ID: 1},
}

for _, item := range items{ // item
	fmt.Println(item.ID)
}
Do
type BigStruct struct{
	ID int
}

items := []BigStruct{
	{ID: 0},
	{ID: 1},
}

for i := range items{ // slice
	fmt.Println(items[i].ID)
}