Summary of the language features of Go

Source: Internet
Author: User

Write in front:
There are a lot of discussions about Golang, and some of the seven Bulls have concluded that the go language will develop rapidly in the future and will probably replace Java as the most popular programming language in the Internet age. The go language is Google's programming language, after the success of the world to create a change in the lives of the operating system, Google seems to feel the need to bring the world a powerful programming language, and the go language relies on its many friendly features are not negative expectations are being contacted by developers, I was fortunate to learn about the go language when I was learning high-performance concurrent programming and decided to learn some of the features of go. I find that there are not so many studies on go that I need to write something myself. Most of the content here comes from the seven-cow team's "Go Language Programming" book. It will also be studied in accordance with the chapters organized in the book. Of course, if some knowledge of the Internet is already available, here directly reproduced.
-written by Lingtao in Nanjing.

http://blog.csdn.net/michael_kong_nju/article/details/45423197

According to the book, The Go language has the following characteristics, which we will introduce separately.
? Automatic garbage collection
? Richer built-in types
? function multiple return value
? Error handling
? Anonymous functions and closures
? Types and Interfaces
? Concurrent programming
? Reflection
? Language interactivity

1. Automatic garbage collection

From c to C + +, from the perspective of program performance, these two languages allow programmers to manage their own memory, including memory requests and releases. Because there is no garbage collection mechanism, C + + is running fast, but with the programmer taking a very cautious view of memory usage. Even a bit of carelessness can lead to a "memory leak" that wastes resources or "wild pointers" that cause programs to crash, even though C++11 later uses the concept of smart pointers, but programmers still need to use them very carefully. Later, in order to improve the speed of program development and the robustness of the program, Java and C # and other high-level languages introduced the GC mechanism, that is, the programmer does not need to consider the memory recycling, but by the language features to provide garbage collector to reclaim memory. But it may be that the program is running less efficiently.
"Go language as a new development language, of course, can not ignore memory management this issue." And because the go language doesn't have C + +
This "powerful" pointer calculation function can naturally contain garbage collection functionality. Because of the garbage collection feature, developers do not need to worry about the object being directed to failure, so the DELETE keyword is not required in the go language and the free () method is not required to explicitly release memory.

2. Richer built-in types

In fact, as a new language, if it is only for a specific purpose, then it is possible that its built-in type is not many, only need to be able to complete my functions, but the go language "not only supports the simple built-in types supported by almost all languages (such as Integer and float, etc.), but also support some other advanced types, For example, the dictionary type, map to know that these types in other languages are introduced in the form of a package external data type. Array slicing (Slice), similar to the vector in C + + STL, is also a built-in data type used as a dynamic array in go. Here is a fairly simple explanation: "Since the vast majority of developers need to use this type, why should everyone write an import statement to contain a library?" ”

3. Support function multiple return value

In c,c++, including some other high-level languages, multiple function return values are not supported. But this feature is really needed, so in c it is generally done by defining the return value as a struct, or by returning it in the form of a function's argument reference. In the go language, as a new language, the goal is to locate a powerful language, of course, can not give up the satisfaction of this demand, so support function multiple return value is necessary, for example:

return"May""M""Chen""Babe"//定义了一个多返回值的函数getNamefn, mn, ln, nn := getName()      //调用赋值>  ___//缺省调用
4. Error handling

In the traditional OOP programming, in order to catch the robustness of the program needs to catch the exception, most of the methods used are try () catch{} module, for example, in the following Java code, you may want to do:

...;try {    ...;    ...//别的一些异常捕获finally {    stmt.close();    }finally {    conn.close(); }

In go, three keywords are introduced, namely defer, panic, and recover, where the use of the DEFER keyword statement means that the code is executed automatically when the function exits, regardless of whether the program has an exception.
So above your Java code with Go process rewrite only two lines:

...defer conn.Close()

The other two keywords are discussed later. So "Go language error-handling mechanism can reduce the amount of code, so that developers do not need just for the sake of program security to add a lot of a layer of try-catch statement." This is also a good thing for code readers and maintainers, because you can avoid locating business code in layers of code nesting. ”

5. Anonymous functions and closures

The introduction of this feature is not much, presumably, that functions in go can also be passed as parameters:
"In the Go language, all functions are also value types and can be passed as parameters. The Go language supports regular anonymous functions and closures, such as the following code, which defines an anonymous function called F, which the developer can freely pass and invoke on the anonymous function variable:
F: = func (x, y int) int {
return x + y
}

6. Types and Interfaces

This feature is some of the features of go when it comes to the implementation of OPP, mainly with these points:
First: The go language does not have a very complex object-oriented concept, that is, there is no inheritance and overloading, its type is more like a struct in C, and directly uses the struct keyword, is only the most basic type combination function. However, although these syntactic features are not supported, the go OOP can also implement these functions, but the form of implementation will be different.
That is, the concept of a "non-intrusive" interface that needs to be described here.
As an example:
In C + +, it is common to define an interface and a type of

Abstract interface
Interface IFly
{
virtual void Fly () = 0;
};
Implementation class
Class Bird:public IFly
{
Public
Bird () {}
Virtual ~bird () {}
void Fly ()
{
Fly in a bird's way
}
};
When using the
void Main ()
{
ifly* pfly = new Bird ();
Pfly->fly ();
Delete Pfly;
You need yourself to define an interface as a virtual function, and let the type inherit the interface and override the virtual method. Dynamic binding is required when it is used.
To achieve the same functionality in go, you only need to
Type Bird struct {
...
}
Func (b *bird) Fly () {
Fly in a bird's way
}
Type IFly Interface {
Fly ()
}
Func Main () {
var Fly IFly = new (Bird)
Fly. Fly ()
}
As you can see, "while the bird type is implemented, there is no declaration of the relationship with the interface ifly, but the interface and type can be directly
Even if the definition of the interface is not used before the type definition, this relatively loose correspondence can be significantly reduced because the connection
A large number of code adjustments that result from port adjustments. "

7. Concurrent Programming

In fact, so far, the most attractive to me is this feature, and I said before if it is not because of the high concurrency of the server I may not even know the language of go, in the previous article http://blog.csdn.net/michael_kong_nju/article/ details/45420047 discusses why go can achieve a large-scale concurrency principle, here does not do the detailed introduction, only gives the implementation method, namely
The go language introduces the Goroutine concept, which makes concurrent programming very simple. The go language makes concurrent programming lighter and more secure by using the concurrency mechanism of goroutine instead of the bare operating system, and by using message passing to share memory instead of using shared memory to communicate. By using the keyword go before a function call, we can let the function execute in goroutine mode, Goroutine is a more lightweight and resource-saving process than threading. ”
"At the same time, the go language implements the CSP (communication sequence process, communicating sequential process) model as the recommended means of communication between Goroutine, in the CSP model, a concurrent system consists of several sequential processes running in parallel, Each process cannot assign a value to another process's variables. Collaboration between processes can only be achieved through a pair of communication primitives. The go language uses the concept of channel as a lightweight way to implement a CSP model. Channel usage is closer to the concept of piping (pipe) in UNIX systems, which facilitates communication across goroutine. ”
"In addition, because all goroutine created in a process run in the same memory address space, if different goroutine have to access the shared memory variable, the corresponding read-write lock should be acquired before access." The sync pack in the Go Language standard library provides a complete read-write lock function. ”

8. Support Reflection

Here the Reflection (Reflecttion) is similar to the reflection in Java, which can be used to get the trust information of the object type and manipulate the object dynamically. Because reflection can have a significant effect on the readability of a program, some of the features of reflection are implemented in go only where reflection support is particularly needed. The most common use scenario for reflection is to serialize objects (serialization, sometimes called Marshal & Unmarshal). For example, the Encoding/json, Encoding/xml, Encoding/gob, encoding/binary and other packages of the Go Language standard library are heavily dependent on reflection. ”

9. The Interactivity of language

The interactivity here is mainly the interaction with C, because the developer of the Go language is the first Bell Labs to create UNIX systems and the C language of the General people, including:
Ken Thompson (Ken Thompson,http://en.wikipedia.org/wiki/ken_thompson): designed the B language and C language, created the UNIX and Plan 9 operating system, 1983 Turing Award winner, The co-author of the Go language.
Most of the C modules are reused directly in the go language, which is known as CGO.CGO, which allows developers to mix and write C code, and the CGO tool can extract the mixed C code and generate a call wrapper code for C functionality. Developers can basically completely ignore how the go language and C language boundaries are crossed.
For example, in a book, the puts function of the C standard library is called directly in the go language.

packagemain/*#include <stdio.h>*/import "C"import "unsafe"funcmain{cstr := C.CString("Hello, world")C.puts(cstr)C.free(unsafe.Pointer(cstr))}

The above is the book summed up in the go language of the 9 features, which I read after reading according to their own experience and some of the book summarizes the summary. For those who want to know the language of go and who are ready to enter the field, there is a general understanding of go. If you want to learn more, you can look at the seven Cow Cloud storage team out of the "Go language programming." I will continue to study later.

Summary of the language features of 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.