Write an authentic Go code

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The most authentic go code is the code of the Go standard library, and when available, you can see how Google's engineers are doing it.

1. Notes

You can use *////or add comments,//There should be a space after
If you want to add comments to the header of each file, you need to add a blank line to the copyright note and the package, or the copyright note will be used as a comment

// Copyright 2009 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file./*Package net provides a portable interface for network I/O, includingTCP/IP, UDP, domain name resolution, and Unix domain sockets.......*/package net......

Note: The note should use a complete sentence, the first word of the note should be the indicator to be annotated, so that it is easy to find in Godoc;
Comments should . end with;

2. Declaration Slice

Use this method to declare slice:

var s []string

Instead of the following format

t := []string{}

Note: The former declares a nil slice, while the latter declares a non-slice with a length of 0 nil

3. Case of String

The error string should not be capitalized and should be written as:

fmt.Errorf("failed to write data.")

Rather than written:

fmt.Errorf("Failed to write data")

Because these strings may be concatenated with other strings, the combined string is abrupt if the words that begin with a capital letter are in the middle, unless these initials are fixed-use words.

Note: Abbreviations must be consistent, such as uppercase URLs or lowercase URLs;
Solid is generally declared as maxlength, instead of dividing max_length or maxlength with the following dashes;

4. Handling error rather than panic or ignoring

For the robustness of the code, do not use _ Ignore the error, but to deal with each error, although the code is cumbersome to write and do not ignore the error;

Try not to use panic;

5. Some names

The package name should be in the singular form, such as Util,model, not utils,models;

Receiver's name should be abbreviated, typically using one or two characters as receiver's name, such as:

func (f foo) method {    ...}

Some words may be written in a variety of ways, and should be consistent in the project, such as the Golang used:

// marshaling// unmarshaling// canceling// cancelation

Instead of:

// marshalling// unmarshalling// cancelling// cancellation

6. Empty string Check

The right way:

if s == "" {    ...}

Instead of:

if len(s) == 0 {    ...}

Not even:

if s == nil || s == ""{    ...}

7. Non-empty slice check

The right way:

if len(s) > 0 {    ...}

Instead of:

if s != nil && len(s) > 0 {    ...}

8. Direct use of BOOL values

For variable var b bool of type bool, use it directly as a judgment instead of comparing it with True/false
The right way:

if b {    ...}if !b {    ...}

Instead of:

if b == true {    ...}if b == false {    ...}

9. Comparison of Byte/slice/string equality

var s1 []bytevar s2 []byte    ...bytes.Equal(s1, s2) == 0bytes.Equal(s1, s2) != 0

Instead of:

var s1 []bytevar s2 []byte    ...bytes.Compare(s1, s2) == 0    bytes.Compare(s1, s2) != 0

10. Check if a substring is included

strings should be used. Containesrune, Strings. Containesany, Strings. Contains

11. Copy Slice

Use the built-in function copy instead of traversing slice one-by-one
The right way

var b1, b2 []bytecopy(b2, b1)

12. Try to shorten the IF

The right way:

  var a, b int  ...  return a > b

Instead of:

    var a, b int    ...    if a > b {        return true    } else {        return false    }

13. Simplify Range

The right way:

    for range m {        ...    }

Instead of:

       var m map[string]int       for _ = range m {     }    for _, _ = range m {    }

14. Use strings. Trimprefix/strings. Trimsuffix

The right way:

    var s1 = "a string value"    var s2 = "a "    var s3 = strings.TrimPrefix(s1, s2)

Instead of:

       var s1 = "a string value"       var s2 = "a "       var s3 string    if strings.HasPrefix(s1, s2) {         s3 = s1[len(s2):]    }

15.append Slice

The right way:

    var a, b []byte    a = append(b, a...)

Instead of:

    var a, b []byte    for _,v range a {        append(b, v)    }

Reference documents


Effective Go

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.