其他分享
首页 > 其他分享> > go语言风格培训

go语言风格培训

作者:互联网

go语言风格培训

参考资料

Declaring Empty Slices

goodbad
var t []stringt := []string{}

Error Strings

goodbad
use fmt.Errorf(“something bad”)fmt.Errorf(“Something bad.”)

Handle Errors

Imports

package main

import (
	"fmt"
	"hash/adler32"
	"os"

	"appengine/foo"
	"appengine/user"

	"github.com/foo/bar"
	"rsc.io/goversion/version"
)

Indent Error Flow

GOOD:

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

BAD:

if err != nil {
	// error handling
} else {
	// normal code
}

GOOD:

x, err := f()
if err != nil {
	// error handling
	return
}
// use x

BAD:

if x, err := f(); err != nil {
	// error handling
	return
} else {
	// use x
}

Initialisms

goodbad
sql.DBsql.SqlDB
http.Serverhttp.HTTPServer
list.Listlist.NewList

Package Names

File Name

Chan

Receive Type

Interface assert

GOOD:

t,ok := i.(string)
if !ok {
    //xxxx
}

BAD:

t := i.(string) // panic when i is not string, such as nil

Switch

switch signal {
case syscall.SIGHUP:
    // xxxx
case syscall.SIGQUIT,syscall.SIGTERM,syscall.SIGINT:
    // xxx
default:
    // xxx
}

Table Driven Tests

package main

import (
	"testing"
)

func TestGetCurrTasksCount(t *testing.T) {
	testCases := []struct {
		name          string
		appID         int
		speed         int
		learnedWords  int64
		todayLearnCnt int64
		expect        int
	}{
		{
			name:          "测试今天任务数不满足用户设置每日速度",
			appID:         context.APPPinYin,
			speed:         10,
			learnedWords:  40,
			todayLearnCnt: 8,
			expect:        10,
		},
		{
			name:          "测试今天任务数满足用户设置每日速度",
			appID:         context.APPPinYin,
			speed:         10,
			learnedWords:  60,
			todayLearnCnt: 1,
			expect:        4,
		},
		{
			name:          "测试已经没有可学任务了",
			appID:         context.APPPinYin,
			speed:         10,
			learnedWords:  63,
			todayLearnCnt: 0,
			expect:        0,
		},
	}

	for _, tt := range testCases {
		t.Run(tt.name, func(t *testing.T) {
			resp, err := getCurrTasksCount(test.NewCtx(), tt.appID, tt.speed, tt.learnedWords, tt.todayLearnCnt)
			require.Nil(t, err)
			require.Equal(t, tt.expect, resp)
		})
	}
}

标签:接收器,培训,语言,err,tt,类型,go,string,指针
来源: https://blog.csdn.net/oXiaoBuDing/article/details/117357266