当前位置:网站首页>1_ Introduction to go language

1_ Introduction to go language

2022-07-06 20:37:00 RenLJ1895

About Go Introduction to language

Learning goals

  • Use Go Language solves modern computing problems
  • Use Go Language tools

1. use Go Solve modern programming problems

​ Go The language development team has spent a long time solving the problems faced by today's software developers . When developers choose a language for a project , Have to choose between rapid development and performance .C and C++ This kind of language provides fast execution speed , and Ruby and Python This kind of language is good at rapid development .Go Language builds a bridge between the two , It not only provides high-performance language , It also makes development faster .

​ exploring Go In the process of language , Readers will see carefully designed features and concise Syntax . As a language , Go It not only defines what can be done , It also defines what you can't do .Go The syntax of the language is so simple that there are only a few keywords , Easy to remember .Go The language compiler is very fast , Sometimes people don't even feel like they're compiling . therefore ,Go Developers can significantly reduce the time waiting for the project to build . because Go Language built-in concurrency mechanism , So you don't have to use a specific thread library , Can make the software expand , Use more resources .Go The type system of language is simple and efficient , No extra mental effort is required for object-oriented development , Let developers focus on code reuse .Go The language also comes with its own garbage collector , There is no need for users to manage their own memory . Let's take a quick look at these key features .

1.1 Speed of development

Compile a large C perhaps C++ The project took even longer than going for a cup of coffee . chart 1-1 yes XKCD A cartoon in , Describes the classic excuse for deserting in the office .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-DdTFzYM2-1644673438393)(C:\RenL\code\GOINACTION\image\image-20220212211626891.png)]

​ Go The language uses a smarter compiler , And simplify the algorithm to solve dependency , Finally, it provides faster compilation speed . compile Go The program , The compiler will only focus on those directly referenced Libraries , Not like it Java、C and C++ like that , To traverse all dependent libraries in the dependency chain . therefore , quite a lot Go The program can be 1 Compile in seconds . On modern hardware , Compile the whole Go The source tree of the language only needs 20 second .

​ Because there is no intermediate process from compiling code to executing code , Writing an application in a dynamic language can quickly see the output . The price is , Dynamic languages do not provide the type safety features provided by static languages , We have to often use a large number of test suites to avoid type errors when running bug.

​ Imagine , Use similar JavaScript This dynamic language develops a large application , There is a function that expects to receive a call ID Field of . This parameter should be an integer , Is string , Or a UUID? To know the answer , You can only look at the source code . You can try to use a number or string to execute this function , See what happens . stay Go In language , Don't worry about it at all , Because the compiler can help users catch this type of error .

1.2 Concurrent

​ As a programmer , It is difficult to develop applications that can make full use of hardware resources . Modern computers all have multiple cores , But most programming languages don't have effective tools to make use of these resources easily . These languages need to write a lot of thread synchronization code to take advantage of multiple cores , It's easy to make mistakes .

​ Go The language's support for concurrency is one of the most important features of this language .goroutine Much like threads , But it takes up far less memory than threads , Using it requires less code . passageway ( channel) It's a built-in data structure , Can let the user in different goroutine Send messages with type synchronously between . This makes the programming model more inclined to goroutine Sending messages between , Instead of having multiple goroutine Fight for the right to use the same data . Let's look at the details of these features .

1.goroutine

​ goroutine Yes, with others goroutine Functions executed in parallel , It will also interact with the main program ( Program population ) Parallel execution . In other programming languages , You need threads to do the same thing , And in the Go The same thread will be used in the language to execute multiple goroutine. for example , The user is writing a Web The server , Want to handle different at the same time Web request , If you use C perhaps Java, You have to write a lot of extra code to use threads . stay Go In language ,net/http The library directly uses the built-in goroutine. Each received request is automatically in its own goroutine In the processing .goroutine Uses less memory than threads ,Go The language runtime automatically schedules execution on a configured set of logical processors goroutine. Each logical processor is bound to an operating system thread ( See the picture 1-2 ). This makes the user's application execution more efficient , And the development workload is significantly reduced .

​ If you want to execute a piece of code at the same time , Do something else in parallel ,goroutine It's a good choice . Here is a simple example :

func log (msg string) {
    
    ... Here are some logging code 
}

//  Errors have been detected in some parts of the code 
go log(" Something terrible happened ")

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-1zgeyVKx-1644673438395)(C:\RenL\code\GOINACTION\image\image-20220212211808243.png)]
keyword go Is the only code that needs to be written , Dispatch log Functions as independent goroutine To run , In order to communicate with others goroutine Parallel execution . This means that the rest of the application executes in parallel with logging , Often this parallelism makes end users feel better . Like I said before , goroutine Less resources , So you can often start thousands of goroutine.

2. passageway channel

​ A channel is a data structure , It can make goroutine Secure data communication between . Channel can help users avoid the common problems of shared memory access in other languages .

​ The hardest part of concurrency is to ensure that other processes run concurrently 、 Thread or goroutine You won't accidentally modify the user's data . When different threads modify the same data without synchronization protection , There will always be disasters . In other languages , If you use global variables or shared memory , Complex locking rules must be used to prevent asynchronous modifications to the same variable .

​ To solve this problem , Channel provides a new mode , So as to ensure the data security during concurrent modification . The channel mode ensures that there will only be one at a time goroutine Modifying data . Channels are used to run in several goroutine Send data between . In the figure 1-3 You can see an example of how data flows . Imagine an application , There are multiple processes that need to read or modify certain data in sequence , Use goroutine And channel , You can build a safe model for this process .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-FLWn9JTm-1644673438396)(C:\RenL\code\GOINACTION\image\image-20220212211846720.png)]

​ chart 1-3 There is 3 individual goroutine, also 2 A channel without cache . first goroutine Pass the data through the channel to the second one who is already waiting goroutine. In two goroutine The data transmitted between is synchronous , Once the transmission is complete , Two goroutine Will know that the data has been transmitted . When the second goroutine Use this data to accomplish its task
After business , Pass this data to the third waiting goroutine. This transmission is still synchronous , Two goroutine Will confirm that the data transmission is completed . This kind of goroutine The method of securely transferring data between does not require any lock or synchronization mechanism .

​ It's important to note that , The channel does not provide cross goroutine Data access protection mechanism . If a copy of the data is transmitted over the channel , Then each goroutine All have a copy , It's safe to make changes to your copy . When transmitting a pointer to data , If reading and writing are made up of different goroutine Accomplished , Every goroutine Additional synchronization actions are still required .

1.3 Go The type system of language

​ Go Language provides a flexible 、 No inherited type system , Reuse code to the greatest extent without reducing performance . This type system still supports object-oriented development , But it avoids the traditional object-oriented problem . If you've ever been in a complex Java and C++ Spend weeks thinking about how to abstract classes and interfaces , You'll realize Go How simple the type system of a language is .Go Developer use combination ( composition) Design patterns , Simply embed one type into another , Can reuse all functions . Other languages can also use combinations , But it has to be tied to inheritance , As a result, the whole usage is very complicated , It's hard to use. . stay Go In language , One type is composed of other smaller types , Avoid the traditional inheritance based model .

​ in addition ,Go The language also has a unique interface implementation mechanism , Allow users to model behavior , Instead of modeling types . stay Go In language , There is no need to declare that a type implements an interface , The compiler will determine whether an instance of a type conforms to the interface being used .Go Many interfaces in the standard library are very simple , Only a few functions are open . In practice , Especially for those who use similar Java For people with object-oriented languages , It will take some time to get used to this feature .

1. Simple type

​ Go Languages are not only similar int and string Such built-in types , It also supports user-defined types . stay Go In language , User defined types usually contain a set of typed fields , For storing data .Go Looks like a user-defined language C The structure of language is very similar to , It's also very similar . however Go The type of language can declare the party that operates the type of data
Law . Traditional languages use inheritance to extend structures ——Client Inherited from User, User Inherited from Entity, Go Language is different ,Go Developers build smaller types ——Customer and Admin, Then combine these small types into larger types . chart 1-4 Shows the difference between inheritance and composition .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-JbAOETO6-1644673438397)(C:\RenL\code\GOINACTION\image\image-20220212212021804.png)]

2.Go Interfaces model a set of behaviors

​ Interfaces are used to describe the behavior of types . If an instance of a type implements an interface , This means that this instance can perform a specific set of behaviors . You don't even need to declare that this instance implements an interface , Just implement this set of behaviors . Other languages call this feature duck type one if it calls like a duck , Then it could be a duck .Go That's what language interfaces do . stay Go In language , If a type implements all the methods of an interface , Then the instance of this type can be stored in the instance of this interface type , No additional declaration is required .

​ Similar to Java In this strictly object-oriented language , All designs revolve around interfaces . Before coding , Users often have to think about a huge inheritance chain . Here's a Java Examples of interfaces :

interface User {
    
    public void login();
    public void logout();
}

​ stay Java To implement this interface , It is required that the user's class must meet User All constraints in the interface , And explicitly declare that this class implements this interface . and Go Language interfaces generally describe only a single action . stay Go In language , One of the most commonly used interfaces is io.Reader. This interface provides a simple method , Used to declare that a type has data
Can read . Other functions in the standard library can understand this interface . The definition of this interface is as follows :

type Reader interface {
    
    Read(p []byte) (n int, err error)
}

​ In order to achieve io.Reader This interface , You just need to achieve one Read Method , This method accepts a byte section , Returns an integer and possible errors .

​ This is essentially different from the interface system of traditional object-oriented programming language .Go The interface of language is smaller , Only tend to define a single action . In practice , This makes it easier to reuse code using composition . Users can implement... For almost all types that contain data io.Reader Interface , Then pass the instance of this type to any one who knows how to read
io.Reader Of Go function .

​ Go The entire Web Library of the language uses io.Reader Interface , In this way, the function of the program can be separated from the implementation of different networks . This interface is interesting to use 、 Elegant and free . file 、 buffer 、 Sockets and other data sources are implemented io.Reader Interface . Using the same interface , Can operate data efficiently , Without considering the data
Where are from .

1.4 memory management

Improper memory management can lead to program crash or memory leak , Even crash the entire operating system .Go Language has a modern garbage collection mechanism , Can help you solve this problem . In other system languages ( Such as C perhaps C++) in , Allocate this memory before using it , And release it after use . Even if you do one thing wrong , Can cause program crashes or memory leaks . unfortunately , Tracking whether memory is still in use is itself a very difficult thing , To support multithreading and high concurrency , It makes it even more difficult . although Go Language garbage collection will have some additional overhead , But when programming , It can significantly reduce the difficulty of development .Go Language gives boring memory management to professional compilers , And let programmers focus on more interesting things .

Go Language memory management ( One ): System memory management - cloud + Community - Tencent cloud (tencent.com)

Go Language memory management ( Two ):Go memory management - cloud + Community - Tencent cloud (tencent.com)

2. Hello ,Go

The easiest way to feel a language is to practice . Let's see how it works Go How to write classic HelloWorld! Applications :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-3mqL5gjo-1644673438398)(C:\RenL\code\GOINACTION\image\image-20220212212147224.png)]

After running this sample program, we will output a familiar sentence on the screen . But how does it work ? There is no need to install Go Language , Almost all can be used in the browser Go The function of language .

Go Playground

Go Playground Allow editing and running... In the browser Go The language code . Open it in a browser https://go.dev/play/. The code displayed in the browser is editable ( See the picture 1-5). Click on Run, See what happens .
You can change the output greeting text into another language . Try to change fmt .Println() The words inside , Then click... Again Run.

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-VjRgPDUz-1644673438399)(C:\RenL\code\GOINACTION\image\image-20220212214115372.png)]

Share Go Code Go Developers use Playground Share their ideas , Test theory , Or debug the code . You can do the same . Each use Playground After creating a new program , You can click on the Share Get a website for sharing . Anyone can open this link . https://go.dev/play/p/MAohLsrz7JQ

3. Summary

  • Go Language is modern 、 fast , With a powerful standard library .
  • Go The language has built-in support for concurrency .
  • Go Language uses interface as the basic module of code reuse .
原网站

版权声明
本文为[RenLJ1895]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131159522777.html