Introduce some programming languages — Go language

Introduce some programming languages ​​— Go language

Go language

Introduction

The Go language (or Golang) originated in 2007 and was officially released in 2009. Go is a very young language, and its main goal is "combining the development speed of dynamic languages ​​​​such as Python with the performance and security of compiled languages ​​​​such as C/C++".

The Go language is another attempt at programming language design and a major improvement over C-like languages. It not only allows you to access the underlying operating system, but also provides powerful support for network programming and concurrent programming. The Go language has many uses and can be used for network programming, system programming, concurrent programming, and distributed programming.

The introduction of the Go language aims to reduce the complexity of the code without losing the performance of the application. It has the advantages of "simple deployment, good concurrency, good language design, and good execution performance". At present, many IT companies in China have adopted Go. Language development projects.

The Go language is sometimes described as a "C-like language", or "the C of the 21st century". Go inherits from C language similar expression syntax, control flow structure, basic data types, call parameter value passing, pointer and many other ideas, as well as the operating efficiency of compiled machine code and the existing Seamless adaptation of the operating system.

Because the Go language has no concepts of classes and inheritance , it doesn't look the same as Java or C++. But it implements polymorphism through the concept of interface . The Go language has a clear and easy-to-understand lightweight type system, and there is no hierarchy between types. Therefore, it can be said that the Go language is a hybrid language .

Additionally, many important open source projects are developed in Go, including Docker, Go-Ethereum, Thrraform, and Kubernetes.

Founder of Go language

When evaluating a language, it is important to understand the motivations of the designers and the problems that the language is intended to solve. The Go language comes from the hands of Ken Thompson and Rob Pike, Robert Griesemer, who are all heavyweights in the field of computer science .

  1. Ken Thompson

A member of the Unix team at Bell Labs, one of the founders of C language, Unix and Plan 9, in the 1970s, designed and implemented the original UNIX operating system. From this point of view, how can his contribution to computer science be emphasized? Not too much. He also collaborated with Rob Pike on the design of the UTF-8 encoding scheme.

  1. Rob Pike

The general director of the Go language project and a member of the Unix team of Bell Labs. In addition to helping design UTF-8, he also helped develop the distributed multi-user operating system Plan 9, the Inferno operating system and the Limbo programming language, and co-authored " The Unix Programming Environment", made an orthodox elaboration on the design concept of UNIX.

  1. Robert Griesemer

Worked at Google, participated in the development of the Java HotSpot virtual machine, has a deep understanding of language design, and is responsible for the code generation part of Google's V8 JavaScript engine used by Chrome browser and Node.js.

These heavyweights in the field of computer science designed the Go language to meet the needs of Google. It took two years to design the language, incorporating the entire team's years of experience and deep knowledge of programming language design. The design team drew on the design wisdom of Pascal, Oberon, and C, while giving Go the convenience of a dynamic language. Therefore, the Go language embodies the language design philosophy of experienced computer scientists and is designed for one of the world's largest Internet companies.

All the designers of the Go language say that they designed the language because C++ brought them frustration. In the Go Design Team meetup at Google I/O 2012, Rob Pike had this to say:

We do a lot of C++ development and get tired of waiting for compilation to finish, and while this is a joke, it's largely true.

The main function

The syntax of Go is close to that of C language, but the declaration of variables is different. Go supports garbage collection. Go's parallelism model is based on Tony Hall's Communicating Sequential Processes (CSP), and other languages ​​that follow a similar model include Occam and Limbo, but it also has Pifeatures of operations, such as channeling. at 1.8 1.8In version 1.8 , the support of plugins (Plugin) is opened, which means that some functionscan be dynamically loaded from Go.

Compared with C++, Go does not include functions such as enumeration, exception handling, inheritance, generics, assertions, virtual functions, etc., but adds features such as slice (Slice) type, concurrency, pipeline, garbage collection, interface (Interface) and so on language-level support for . Version 2.0 of Go will support generics, take a negative stance on the existence of assertions, and justify itself by not providing type inheritance.

Unlike Java, Go has built-in associative arrays (also called Hashes or Dictionaries), just like string types.

Features of the Go language

simple grammar

Leaving aside the grammatical style, in terms of types and rules alone, Go has many similarities with C99 and C11 , which is also an important reason why the Go language is named "NextC".

**The syntax of the Go language is at the extremes of simplicity and complexity. **The C language is so simple that every time you write a line of code, you can imagine in your mind what it looks like after compilation, how instructions are executed, how memory is allocated, and so on. The complexity of C is that it has too many obscure and marginal rules, which is really a headache. In comparison, Go starts from scratch and has no historical burden. After learning many lessons, it can plan a world with strict rules and simple order from scratch .

The grammatical rules of the Go language are strict, there is no ambiguity , and there is no black magic variation usage. Anyone who writes the code is basically the same, which makes the Go language easy to learn. I think it is worthwhile to give up some "flexibility" and "freedom" in exchange for better maintainability.

The benefits of downgrading ++, --from operators to statements, preserving pointers, but blocking pointer arithmetic by default, are obvious. Also, using slices and dictionaries as built-in types and optimizing them at runtime is considered "simple".

concurrency model

Today, concurrent programming has become a basic skill for programmers, and many discussion topics related to it can be seen in various technical communities. In this case, the Go language has done a very bold thing uncharacteristically, fundamentally making everything concurrent, and running everything with at runtimeGoroutine , including main.mainthe entry function.

Arguably Goroutinethe most notable feature of Go. It uses a coroutine-like way to handle concurrent units, but it does a deeper optimization at the runtime level. This makes syntactically concurrent programming extremely easy, no need to deal with callbacks , no need to pay attention to thread switching, only one keyword, simple and natural.

Matching channelto realize the CSP model. Dismantling the data coupling between concurrent units and performing their duties is a relief that all developers who struggle with memory sharing and lock granularity can expect. If there are deficiencies, it is that there should be a bigger plan to expand communication from within the process to outside the process to achieve true distribution .

memory allocation

It is good to make everything concurrent, but it also brings many problems. How to realize memory allocation and management under high concurrency is a difficult problem. Fortunately, Go chose it tcmalloc, which is a high-performance memory allocation component designed for concurrency.

It can be said that the memory allocator is the least changed part of the three major components of the runtime. The memory allocator completely retains the original architecture of tcmalloc, excluding the modified content due to the cooperation with the garbage collector. Use cache to provide lock-free allocation for the current execution thread, and multiple centrals balance memory unit reuse among different threads. At a higher level, the heap manages a large block of memory to be divided into multiplexed memory blocks of different levels. The fast allocation and secondary memory balance mechanism enable the memory allocator to perform memory management tasks under high pressure.

Compiler optimizations have been very effective in the last few releases. It will try its best to allocate objects on the stack to reduce garbage collection pressure, reduce management consumption, and improve execution performance. It can be said that we basically do not need to participate in memory management operations, except for occasional performance issues where we are forced to use object pools and autonomous memory management.

garbage collection

Garbage collection has always been a problem. In the early years, Java was ridiculed for a long time due to the inefficiency of garbage collection. Later, Sun continuously absorbed a lot of people and technology to develop to today. But even so, in large-memory application scenarios such as Hadoop, garbage collection is still stretched and difficult.

Compared to Java, Go faces more difficulties. Due to the existence of pointers, reclaimed memory cannot be shrunk. Fortunately, pointer arithmetic is blocked, otherwise it would be difficult to achieve precise recovery.

Every time you upgrade, the garbage collector must be the most modified part of the core components. From concurrent cleaning, to reducing STW time, until Go version 1.5 implements concurrent marking, gradually introducing three-color marking and write barriers, etc., all are to make garbage collection work better without affecting user logic. Despite the efforts, the current version of the garbage collection algorithm can only be said to be usable, and there is still a lot of distance from being easy to use.

static link

When Go was first released, static linking was advertised as a virtue. It only needs to be compiled as an executable file, and it can be deployed without adding anything . This seemed to be a good thing, but then the mood changed. For several consecutive versions, the compiler is improving buildmodethe function of the dynamic library, and the scene becomes a bit embarrassing for a while.

Leaving aside unfinished buildmodepatterns, the benefits of static compilation are obvious. The runtime and dependent libraries are directly packaged into the executable file, which simplifies the deployment and release operations, without the need to install the runtime environment and download many third-party libraries in advance. This simplicity is of great benefit when writing system software, since library dependencies have always been a hassle .

standard library

Full-featured, reliable standard libraries provide plenty of power for programming languages. Most of the basic function development can be completed without the help of third-party extensions, which greatly reduces the cost of learning and use. The most important thing is that the standard library has upgrade and repair guarantees, and can also obtain the convenience of deep optimization from runtime , which is not available in third-party libraries.

Although the Go standard library cannot be said to be fully covered, it is also extremely rich . Among them, it is commendable net/httpthat a high performance can be achieved with only a few simple statements Web Server, which has always been the highlight of publicity. What's more, a large number of excellent third parties based on this Frameworkhave pushed Go to Web/Microservicethe position of one of the development standards.

Of course, excellent third-party resources are also an important part of the language ecosystem. Among the several languages ​​that have emerged in recent years, Go is unique, and a large number of excellent works emerge frequently, which also provides a good reference for us to learn Go.

tool chain

A complete toolchain is extremely important for day-to-day development. Go does a pretty good job here, whether it is compilation, formatting, error checking, help documentation, or third-party package download and update, there are corresponding tools. Its functions may not be perfect, but at least it is easy to use.

A complete built-in testing framework, including unit testing, performance testing, code coverage, data competition, and tuning pprof, is an essential tool to ensure that the code can run correctly and stably.

In addition, runtime monitoring information can be output through environment variables, especially garbage collection and concurrent scheduling tracking , which can further help us improve the algorithm and achieve better runtime performance.

mascot

The Go language has a mascot, and conferences, documentation pages, and blog posts mostly include the Go Gopher pictured below, designed by the talented illustrator Renee French, who is also the wife of one of Go's designers, Rob Pike.

simple program

Output "Hello World!"

package main 

import (
    "fmt" 
)

func main() {
    
     
    fmt.Println("Hello World!")
}

A + B problem

package main
import "fmt"
func main() {
    
    
    var a, b int
    fmt.Scanf("%d%d", &a, &b)
    fmt.Println(a+b)
}

Implement a simple HTTP server

package main

import (
    "net/http"
)

func main() {
    
    
    http.Handle("/", http.FileServer(http.Dir(".")))
    http.ListenAndServe(":8080", nil)
}

Guess you like

Origin blog.csdn.net/ZH_qaq/article/details/131260383