Golang-Detailed Go language code specification

This article originated from a personal public account : TechFlow , original is not easy, seek attention


Today is the second part of the Golang topic . Let ’s take a look at Go ’s language specification.

Before we continue with today ’s content, let ’s answer a question.

Some students asked me in the background, why Golang is more suitable for the development of distributed systems ? Does it have any advantages over Java?

In fact, answering this question involves many concepts, such as many concepts in the operating system about processes, threads, coroutines and so on. We will simplify these contents and give an example of the simplest thread. Let's write an example of multithreading in java :

public class MyThread implemnts Runnable {
    public void run() {
      System.out.println("I am a thread")
    }
}

public class Test {
    public static void main(String args[]) {
        MyThread thread1 = new MyThread();
        thread1.start();
    }
}

Let's take a look at Golang again:

func run() {
    fmt.Println("I am a Thread")
}

func main() {
    go run()
}

Is such a comparison much simpler?

Golang language specification

Everyone knows that one of the biggest differences among programmers is which line should the curly braces be written on , there is another line, and some follow the loop. These two groups of people were divided into two schools, and they fought each other endlessly, and they also spawned many paragraphs.

In order to unify the style, many languages ​​have standardized the code style. For example, Python removes curly braces and uses spaces to indent code. Unfortunately, some people use four spaces for indentation, and others use tabs. The two sides form a camp and quarrel with each other ...

Perhaps the developers of Golang used to suffer from code style quarrels, so Golang did an epoch-making thing, which strictly restricted the code style . Everyone must use the same style to force unification, otherwise they will report to you every minute. Therefore, before we conduct specific grammar learning, we must start with the language specification, otherwise it will be very costly to wait for us to develop a bad habit and then want to correct it. In fact, correcting the code style is a difficult thing. To be honest, my code style is not very good. I always use some simple variables such as cur, pnt, node, u, v. This is also the habit left by playing acm. It would be quite difficult to change it for a while. Therefore, everyone must develop good habits at the beginning, and leave me the bad habits (fog).

package specification

There are many language specifications in Golang, and they cover a wide range of aspects. Some of them are temporarily unavailable. Let ’s pick the basics first. The first is the package specification . For a package, its name should be consistent with the directory. Take a meaningful package name, and do n’t use names that others do n’t understand. Such as test and unit, and can not conflict with the standard library.

The second is that when we quote packets, we need to pay attention not to use relative paths , but to use absolute paths.

// wrong
import "../../../repo"

// correct
import "github.com/repo/package

Of course, we can install a goimport tool to help us automatically import packages. However, automatic package introduction will also have pits, especially when there are two packages with the same name in the directory, errors may be introduced, which needs our own attention.

Code style specifications

The Go language stipulates that we should use the hump standard to name variables, not _. In Go, the first letter capitalizes the variable in the structure or the function public in the package. If it is lowercase, it means private , which needs special attention. When I first started writing go, I was very unaccustomed to it, so stepping on a pit is common.

There are constants in golang. Constants in golang use the camel case standard with the first letter capitalized . For example, if we start a constant called app_env, which means the current app running environment, we must define it like this:

const AppEnv = "env"

Another point is that the designers of Golang thought that adding a semicolon at the end of the line was unnecessary , so the compiler added the function of automatically adding a semicolon at the end of the line. So we can add or not, but it is generally considered unnecessary. So generally speaking, except in the loop body or the judgment conditions, we generally do not write semicolons. Of course, there are special cases, such as when you want to write multiple statements on one line:

var a int; var b float;
a = 3; b = 3.2;

Of course, it is generally not recommended to do this , it is recommended to split into multiple lines, more beautiful.

Another point is that all variables and packages in golang must be used . It is not allowed to define things that are not used, otherwise it will also report an error. In other words, it strictly limits our caution when writing code. You can't apply for unused variables at will. Most languages ​​do not have such restrictions, but golang has restrictions, so we must be careful when writing code.

Another point is about curly braces. In golang, curly braces are strictly restricted from being written on the current line , rather than on a new line.

// wrong
if expression 
{
  ...
}

// correct
if expression {
  ...
}

From the above example, we can also notice that the condition behind if in golang is not enclosed in parentheses , which is the same as Python. But if you are used to writing java or C ++, you may not be comfortable at first.

The last point is that golang's code specification detection tool golint stipulates that all functions and structure headers must be commented , and the specification of comments is also restricted. The specification of the comment is the name plus the description . If it is not written or is not standardized, the code can run, but it cannot pass the golint specification detection. Generally speaking, the company's development environment will be limited, and only code that passes the golint specification can be submitted for release.

// HelloWorld print hello world
func HelloWorld() {
    fmt.Println("Hello World")
}

Another point is that golang does not support implicit type conversions , such as int and int32 and int64, which will be treated as different types. If we assign an int32 variable to the int type, it will cause an error and must be converted manually. This of course increases the work when coding, but also avoids many problems caused by the difference in accuracy.

In addition to these, golang also defines the specification of structure definition and error handling. But for our beginners, these must be understood at present, and other content can be familiar to us when we meet later.

A language that has strict code restrictions on code style may be a pain for beginners , because more things to remember, we must not only learn grammar, but also understand these specifications. But when we are familiar with or work, we will find that this is actually a good thing. For a multi-person collaboration scenario, everyone abides by the same specifications will greatly improve the efficiency of code exchange and collaboration . If you have seen the codes of other people whose code style is completely different from your own, I believe you will have a deeper understanding of this.

to sum up

From the strictness of the specification and the degree of castration of object-oriented , golang is not like a new language, but the style of the old school language of the last century. But Golang has many new features, such as allowing function values ​​to return multiple results , supporting anonymous functions and some functional programming functions, etc. In the beginner stage, I also resisted it very much, probably because Python is too much written and used to dynamic languages. However, with the deepening of my understanding of this language, I have increasingly discovered the thinking and wisdom behind its design concepts, and slowly improved on it. Language, the popularity of these years is not unreasonable.

Another important point is that because golang is so unique, it often makes me think about the intention behind it. This kind of thinking, coupled with consulting some information, can find many blind spots in previous thinking. When I was studying language before, I would never think about why the language designer should design like this. I would only learn the relevant content according to the gourds. In addition to improving the understanding of the language itself, such thinking can also enhance the thinking and understanding of the problem scene . For the engineer, the latter is actually more important.

Of course, I can say that these contents are useless, and you need to experience them carefully in front of the screen.

I hope everyone can feel the charm of golang, and they can grow up and cheer during this process! If you feel something rewarded, please read or repost it. Your effort is very important to me.

Insert picture description here

Published 117 original articles · Like 61 · Visits 10,000+

Guess you like

Origin blog.csdn.net/TechFlow/article/details/105643808