Skip to content

NKN Golang Style Guide

doraemon0 edited this page Jun 22, 2018 · 3 revisions

NKN Golang Style Guide

v0.1 - Last updated Apr 16, 2018

Contents

Detail

1. gofmt and goimports

[rule 1-1] Use gofmt to fix the majority of mechanical style issues.
[rule 1-2] Use goimports to import dependent packages.

2. folders and files

[rule 2-1] Filenames should be all lowercase.
[rule 2-2] Foldernames should be all lowercase.
[rule 2-3] Test file should be like xxx_test.go.

// file  
accountstate.go  
  
// folder  
nkn/core/transaction/payload  
  
// test file  
transaciton_test.go  

3. package

[rule 3-1] Package name should be same with the folder name.

4. import

[rule 4-1] Imported packages are organized in groups: standard packages, inner packages and third party packages. And each group should be separated with blank lines.
[rule 4-2] Imported path should begin with $GOPATH.
[rule 4-3] As few as possible to use alias, except for common package.

import (  
	"os"  
	"sort"  
  
	"github.com/nknorg/nkn/cli/info"  
	"github.com/nknorg/nkn/cli/wallet"  
  
	"github.com/urfave/cli"  
)  

5. comment

[rule 5-1] Comments should begin with the name of the thing being described and end in a period.
[rule 5-2] Perfer line comments to block comments.

// Encode writes the JSON encoding of req to w.  
func Encode(w io.Writer, req *Request) { ...  

6. function

[rule 6-1] It is better to always use camel-case.
[rule 6-2] The first character should be uppercase if this function is accessible outside a package.
[rule 6-3] Functions should be split by a blank line.

func (tx *Transaction) GetMergedAssetIDValueFromReference() (TransactionResult, error) {
	reference, err := tx.GetReference()
	if err != nil {
		return nil, err
	}
	var result = make(map[Uint256]Fixed64)
	for _, v := range reference {
		amout, ok := result[v.AssetID]
		if ok {
			result[v.AssetID] = amout + v.Value
		} else {
			result[v.AssetID] = v.Value
		}
	}
	return result, nil
}

7. variable

[rule 7-1] It is better to always use camel-case.
[rule 7-2] The first character should be uppercase if this variable is accessible outside a package.
[rule 7-3] declaring an empty slice, prefer var t []string

type Transaction struct {
	TxType         TransactionType
	PayloadVersion byte
	Payload        Payload
	Attributes     []*TxAttribute
	UTXOInputs     []*UTXOTxInput
	Outputs        []*TxOutput
	Programs       []*program.Program
	hash           *Uint256
}

8. errors

[rule 8-1] The error return code must be handled.
[rule 8-2] Don't use panic for normal error handling.
[rule 8-3] It's better to use error and multiple return values.

err := tx.DeserializeUnsigned(r)
if err != nil {
	log.Error("Deserialize DeserializeUnsigned:", err)
	return NewDetailErr(err, ErrNoCode, "transaction Deserialize error")
}

9. others

[rule 9-1] Make sure your code in one line at most 120 columns.
[rule 9-2] Use 4-space tabs
[rule 9-3] Must not use magic number.