Leoay’s 8th original article from the tech circle

Word count: 4075

Hello, I’m Leoay and this is another article I’ve been writing for countless days and I promise, this is the last time dove…… (No lies!!)

I have been thinking about it for a long time and don’t know what to write. In fact, I have written half of an article before, but I feel bad, so I shelved it. I originally wanted to write a series of articles about Go language starting from scratch, but I feel there is no need, because there are too many zero-based reference materials.

In the end, I decided to stick to the things I use most and which I think are important. I think it’s a good way to get more bang for your buck.

This article I share today is actually a few days ago in the company to share a part of the article, is also a very basic introduction to Go language, just suitable for this number, so I stole a lazy, direct take.

Today, I would like to share some knowledge about Go language with you, mainly to explain “why I suggest you learn Go language”, I mainly want to start from the following aspects:

  1. A brief introduction to Go

  2. Go language cross-platform

  3. Go language network programming

  4. Concurrent programming of Go language

  5. Go language learning resources to share

Because I learn the language, and use in the work is not a long time, and probably a year, so there must be a understanding and expression in the article is not the right place, of course there will be more comprehensive, also please forgive, if you find wrong place, also please advice, of course I more hope my paper can help to you, Let’s get to the point where the advantages of Go can shine in our daily work.

A brief introduction to Go

Go, also known as Golang, was originally developed in 2007 by three Google engineers, Robert Griesemer, Rob Pike, and Ken Thompson, who wanted to use a new language to improve the development of reliable, robust, and efficient software.

It started out as a small project maintained by the team, but the project became so promising that on November 10, 2009, Google posted the project on its open source blog, and developers from all over the world joined in to maintain and develop the project.

The Go website says that “Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.” From this we can also see some characteristics of Go language, simple, reliable, efficient, in addition, Go language has many other characteristics, such as:

  • The static type

  • Clear syntax (strict syntax format)

  • Cross-platform, local cross-compilation is convenient

  • High compilation efficiency

  • No dependencies at runtime

  • Support garbage collection

  • There is a rich and powerful standard library

In fact, the design inspiration of Go is mainly derived from Oberon, Pascal, C and Alef, etc., which can be taken from the strengths of each language and put so many advantages into one. In fact, Go is designed to solve the complexity of building software when developing applications and building large-scale applications.

If you’ve been using Go for a while, you’ll be impressed by its simplicity and efficiency. It doesn’t bother you with all the features of the language. It doesn’t pit you like C++ does, and it doesn’t pit you like Java or Python, which is syntactically as simple as Python, but in terms of hardware, It’s more like C, where compiled applications are executable binaries.

From the point of view of programming paradigm, Go language and C are “procedural language”, Go language is also like C are “single dog” without “object”, but please do not think that Go does not support object-oriented programming, on the contrary, inheritance, polymorphism and object-based, these features are quite a few. Go is a procedural programming language with an object-oriented spirit at its core (from whimsical nonsense).

Go language cross-platform

Well, after all the talk about the advantages of Go, let’s not talk about the disadvantages of Go. Let’s talk about the cross-platform advantages of Go.

Why cross-platform? Because compilers are cross-platform, like C and C++, Go’s code is compiled by its own compiler into machine-readable binaries and then run directly.

There’s nothing to be said for this, but one of the cool things to say is that Go comes with a cross-compilation tool. For example, if I write some go code on macOS, what if I want to compile something that runs directly on Windows? To do this, install the cross-compile tool chain, modify the Makefile, and then make.

Go, however, requires only a few arguments before compiling the command to cross-compile. Here are some of the arguments used to compile the command for different platforms:

  • Compiling a Linux program

    CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build filename.go

  • Compile Arm Linux programs

    CGO_ENABLED=0 GOOS=linux GOARCH=arm go build filename.go

  • Compiling the Window program

    CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build filename.go

  • Compile MacOS programs

    CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build filename.go

The command above can be run directly on any platform, and can compile the application for the target platform. Mom doesn’t have to worry about us messing around with the toolchain anymore, we just need to focus on our business code, Goooooo!

Go language network programming

Mention Go language, I have to blow the Go language network programming, I think like Go language network programming is very simple and efficient language, we use and cherish.

Why is it efficient? Let me write some code first.

For example, if I wanted to write a Web service using raw Go code (without any third-party Web frameworks), I could write it like this

package main import ( "io" "net/http" "log" ) func HelloLeoay(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "hello, leoay! \n") } func main() { http.HandleFunc("/hello", HelloLeoay) err := http.ListenAndServe(":6666", nil) if err ! = nil { log.Fatal("ListenAndServe: ", err) } }Copy the code

It’s easy to write a Web server that accepts GET requests in a few lines of code, and it’s much easier to use a more efficient third-party Web framework. Gin, Iris, Beego, gRPC(Google’s open RPC framework), Kratos(Site B’s open microservices framework), etc.

Of course, Go language to send get, POST and other network requests is also very convenient, here will not expand to write, you can Go to check interested.

Concurrent programming of Go language

Next, I’d like to focus on the concurrent programming features of the Go language. Although there are many advantages to speak Go, a large number of people choose Go as their target language mainly because of its inherent advantages in concurrent programming.

When it comes to concurrent programming, there are three main aspects:

(1) Multithreaded programming

(2) Multi-process programming

(3) Distributed programming

However, this article will not expand so much, briefly talk about the Go language most commonly used multithreaded programming, in fact, our daily work most commonly used concurrent programming is also multithreaded.

In fact, threads in GO language are different from threads in C/C++ and Java. In GO language, threads are actually represented by Goroutine, but goroutine is more fine-grained than threads. It allows us to execute multiple functions or methods in parallel in the same address space at very low cost. It is much cheaper to create and destroy than threads, and its scheduling is thread independent. Creating a Goroutine in Golang is as simple as using the “go” keyword:

Package main import (" FMT ""time") func learning(){fmt.println ("My first goroutine")} func main() {// Create a goroutine Go learning() time.sleep (1 * time.second) fmt.println ("main function")}Copy the code

As the code above shows, we just need to add the go keyword before the function to create a thread, while other languages such as C/C++, Java, Python, etc., are a bit more complicated.

We know that C/C++ thread communication is based on memory, which can easily lead to a lot of difficult to locate problems, among which the most notorious is “memory”.

Go, however, doesn’t have this problem because it communicates between threads based on messages. Rob Pike famously said, “Don’t communicate by sharing memory; Shared memory by Revised. (R. Pike) “.

What does that mean? To put it bluntly, Go language does not use the way of shared memory communication, but through the way of communication shared memory, in fact, illustrates the way of inter-process communication in Go language.

So how else do you do that? In fact, there is a keyword channel in Go language, which means channel. In fact, it is used for communication. The inter-process communication mentioned above can be realized through this channel.

package main

import "fmt"

func sum(s []int, c chan int) {
 sum := 0
 for _, v := range s {
  sum += v
 }
 c <- sum 
}

func main() {
 s := []int{7, 2, 8, -9, 4, 0}

 c := make(chan int)
 go sum(s[:len(s)/2], c)
 go sum(s[len(s)/2:], c)
 x, y := <-c, <-c

 fmt.Println(x, y, x+y)
}
Copy the code

The code has a channel variable, C, which is used to transmit messages between two Sun processes, which are connected like a telephone line to achieve interprocess communication.

What do you think? It’s smart, it’s safe, and it’s easy.

Go language learning resources to share

Finally, I will simply share some of the resources I used to learn Go, and hope to give some help to those who want to get into the pit.

  1. golang.google.cn/

The first recommended book is of course the Go language website, which contains a variety of tips and very detailed reference documents, from installation, to write the first line of Hello World, to write their own modules, to write a Web service everything, the more recommended book is “Effective Go”, can be said to be essential to start.

In addition, Packages is a reference document for all standard libraries. If you are not familiar with standard libraries, you can find answers in this reference document.

  1. books.studygolang.com/gopl-zh/

The second book is “Go Language Bible”, is also a very classic introduction to the book, in short, learn right

  1. draveness.me/golang/

The third book is DraVENESS’s Go Language Design and Implementation, which is shared on draVENESS’s personal blog. It is well written in terms of typography, graphics, and depth. I recommend it.

  1. Github.com/Terry-Mao/g…

Fourth, I would like to recommend the open source project GOIM of B station, which is an IM (instant communication) framework written with Go. Do you know that the barrage of B station is developed based on this framework? As for other advantages, you can browse github directly. So, don’t hesitate to learn it. Of course, there are other components like Kafka, gRPC, Discovery, etc., so it’s not easy to fully learn

  1. Github.com/go-kratos/k…

Finally, I would like to recommend kratos, the micro-service framework, which is also open source of WEBSITE B. At present, many micro-services in the background of website B are developed based on this framework. According to the official words, it has the following advantages:

  • Simple: no over-design, plain and simple code;

  • Common: The functionality of the base library required for common business development;

  • Efficiency: Improve the efficiency of business iteration;

  • Stability: the basic library has high testability, high coverage, safe and reliable practice on the wire;

  • Robust: Reduce misuse through good base library design;

  • High performance: High performance, but not specific. Hacks are used for performance, and unsafe is introduced.

  • Extensibility: Good interface design to extend the implementation or functionality by adding a new base library directory;

  • Fault tolerance: Designed for failure, a lot of understanding of SRE is introduced, with high robustness;

  • Toolchain: Contains a number of toolchains, such as cache code generation, lint tools, etc.

Ok, today I will simply share these points, because it is the first article, so it is not very deep, more inclined to the nature of popular science, but I think it can help you to have a superficial understanding of Go language, in fact, each part can be expanded in detail, this will be written separately later when there is time.

Go, as the C language in the Internet era, has inherent advantages in both micro services and cloud native. If you have business requirements such as Web side or high concurrency, you can consider whether it is more advantageous to develop with Go language.

Well, that’s all for today’s sharing. Thank you for reading. If you have any questions, please discuss with me.

The above is an excerpt of the article. In fact, I think the biggest advantage of Go language is its simple syntax, simple environment configuration and simple code, which does not require us to write a lot of useless code. I think this is also the reason why most people quickly like Go language.

But, like it or not, the goal is to solve a problem and then use it to generate value, and language is just one of thousands of tools.

In the following articles, I will continue to share in depth all kinds of applications of Go language in actual projects, as well as some open source small projects. Welcome to pay attention to, we grow together, come on together!