Summary of Go Language Features
Preface:
There have been a lot of discussions about Golang recently, and several cool-tech coders have determined that the Go language will develop rapidly in the future, and it is likely to replace Java as the most popular programming language in the Internet era. The Go language is a programming language launched by google. After successfully creating an operating system that changes people's lives, google seems to have the need to bring a powerful programming language to the world, the Go language depends on many of its friendly features and is being accessed by developers. I am lucky to have met the Go language when learning high-performance concurrent programming, after learning about some of the features of Go, it determines the system's learning. I found that there are not many learning materials about Go, so I need to write something by myself. Most of the content here comes from the Go language programming book by the qiniu team. We will also learn from the chapters in the book. Of course, if some knowledge points already exist on the Internet, we will repost them here.
-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 features.
Automatic garbage collection
Richer built-in types
Multiple function return values
Error Handling
Anonymous functions and closures
Types and interfaces
Concurrent Programming
Reflection
Language Interaction
1. Automatic garbage collection
From the perspective of program performance from C to C ++, these two languages allow programmers to manage their own memory, including memory application and release. Because there is no garbage collection mechanism, C/C ++ runs very fast, but it comes with the programmer's careful consideration of memory usage. Even if you are not careful, it may cause "Memory leakage", waste of resources, or "Wild Pointer", causing program crashes. Even though C ++ 11 later used the concept of smart pointer, but the programmer still needs to be very careful with the use. Later, in order to improve the speed of Program Development and program robustness, java and C # and other advanced languages introduced the GC mechanism, that is, the programmer does not need to consider memory collection, etc, instead, the language feature provides a garbage collector to recycle memory. However, the program running efficiency may be reduced.
"The Go language, as a new development language, cannot ignore the issue of memory management. And because the Go language does not have C ++
Such a "powerful" pointer computing function can naturally include the garbage collection function. Because of the support of the garbage collection function, developers do not need to worry about the failure of the objects to which they point. Therefore, the Go language does not need the delete keyword or the free () method to explicitly release the memory ".
2. Richer built-in types
In fact, as a new language, if it is only for a specific purpose, there may not be many built-in types. You only need to be able to complete my functions, however, the Go language not only supports Simple built-in types (such as integer and floating point types) that are supported by almost all languages, but also supports some other advanced types, such as Dictionary types, map needs to know that these types are external data types introduced in other languages in the form of packages. Array slicing (Slice) is similar to the vector in C ++ STL. It is also a built-in data type in Go used as a dynamic array. Here is a simple explanation: "Since most developers need to use this type, why do we have to write a line of import statements to contain a library ?"
3. Support for multiple function return values
In C, C ++, some other advanced languages do not support multiple function return values. However, this function is indeed required. Therefore, in C language, the return value is generally defined as a struct or returned through parameter reference of the function. In the Go language, as a new type of language, a powerful language cannot meet this requirement. Therefore, it is necessary to support multiple function return values. For example:
> Func getName () (firstName, middleName, lastName, nickName string) {> return "May", "M", "Chen ", "Babe"} // defines a function getName> fn, mn, ln, nn: = getName () // call value assignment> _, _, lastName, _: = getName () // default call
4. handle errors
In traditional OOP programming, most of the methods used are try () catch {} modules to capture exceptions for program robustness. For example, in the following java code, the following operations may be required:
Connection conn = ...; try {Statement stmt = ...;... // catch other exceptions finally {stmt. close ();} finally {conn. close ();}
Three keywords are introduced in Go, which areDefer, panic, and recoverThe statement using the defer keyword indicates that the related code is automatically executed when the function exits, regardless of whether the program encounters an exception or not.
Therefore, the above java code is rewritten using the Go process with only two lines:
conn := ...defer conn.Close()
The other two keywords will be discussed later. Therefore, "the error handling mechanism of the Go language can greatly reduce the amount of code, so that developers do not need to add a large number of try-catch statements to ensure program security. This is also a good thing for the readers and maintainers of the Code, because it can avoid locating the Business Code in layers of code nesting ."
5. Anonymous functions and closures
There are not many introductions about this function, that is, functions in Go can also be passed as parameters:
"In the Go language, all functions are value types and can be passed as parameters. The Go language supports regular anonymous functions and closures. For example, the following code defines an anonymous function named f. developers can freely pass and call the anonymous function variables:
F: = func (x, y int) int {
Return x + y
}
"
6. Types and interfaces
This feature is a feature of Go when it implements OPP, mainly including the following:
First, the Go language does not have a complex object-oriented concept, that is, there is no inheritance or overload. Its type is more like struct in C and the struct keyword is directly used, only the most basic type combination function. However, although these syntax features are not supported, Go OOP can also implement these features, but the implementation form will be different.
This section describes the concept of a non-intrusive interface.
For example:
In C ++, an interface and type
// Abstract interface
Interface IFly
{
Virtual void Fly () = 0;
};
// Implementation class
Class Bird: public IFly
{
Public:
Bird (){}
Virtual ~ Bird (){}
Void Fly ()
{
// Fly as a bird
}
};
// When using
Void main ()
{
IFly * pFly = new Bird ();
PFly-> Fly ();
Delete pFly;
} You need to define an interface in the form of a virtual function, and let the type inherit this interface and override the virtual method. Dynamic binding is required during use.
To implement the same functions in Go, you only need
Type Bird struct {
...
}
Func (B * Bird) Fly (){
// Fly as a bird
}
Type IFly interface {
Fly ()
}
Func main (){
Var fly IFly = new (Bird)
Fly. Fly ()
}
It can be seen that "Although the relationship with the interface IFly is not declared during the implementation of the Bird type, the interface and type can be directly
And even the interface definition does not need to be prior to the type definition. This loose correspondence can be greatly reduced because
A lot of code adjustment work caused by port adjustment ".
7. Concurrent Programming
So far, this feature has attracted me the most, and I have mentioned that I may not know the Go language if it is not because of the high concurrency of servers, in the previous article, the http://blog.csdn.net/michael_kong_nju/article/details/45420047 discussed why Go can realize the principle of large-scale concurrency. Here we do not give a detailed introduction, only give the implementation method, that is
"The Go language introduces the goroutine concept, which makes concurrent programming very simple. By using a goroutine instead of a bare operating system's concurrency mechanism, and using message transmission to share memory rather than using shared memory for communication, the Go language makes concurrent programming easier and safer. By using the keyword go before a function call, we can let the function be executed in the goroutine method. goroutine is a cool and resource-saving coroutine than a thread ."
"At the same time, the Go language implements the CSP (communication sequence Process, Communicating Sequential Process) model as the recommended communication mode between goroutines. In the CSP model, A concurrent system consists of several sequential processes that run in parallel. Each process cannot assign values to variables of other processes. Only one pair of communication primitives can be used for collaboration between processes. The Go language uses the channel concept to easily implement the CSP model. The channel usage is similar to the pipe concept in Unix systems, allowing for convenient cross-goroutine communication ."
"In addition, because all goroutines created in a process run in the same memory address space, if different goroutines have to access the shared memory variables, the read/write lock should be obtained before access. The sync package in the Go language standard library provides a complete read/write lock function ."
8. Reflection supported
Reflecttion is similar to reflection in JAVA. It can be used to obtain trust information of object types and operate objects dynamically. Reflection may affect the readability of the program. Therefore, in Go, reflection functions are implemented only in areas that require special reflection support. "The most common use case of reflection is serialization of objects, which is sometimes called Marshal & Unmarshal ). For example, packages such as encoding/json, encoding/xml, encoding/gob, and encoding/binary of the Go language standard library depend heavily on the reflection function ."
9. Language Interaction
The interaction here is mainly about the interaction with C. The reason is that the Go language developer was the average person who originally created the Unix System and C language in Bell Labs, including:
Ken Thompson: Co-author of the Go language, who designed language B and C, and created Unix and Plan 9 operating systems.
Most of the C modules are directly reused in the Go language, which is called Cgo. cgo allows developers to write C language code in a hybrid manner. Then, the Cgo tool can extract the Mixed C code and generate the call packaging code for C functions. Developers can basically ignore how the boundaries between the Go language and the C language are crossed.
For example, in the example in the book, The Go language directly calls the puts function of the C standard library.
package main/*#include <stdio.h>*/import "C"import "unsafe"func main() {cstr := C.CString("Hello, world")C.puts(cstr)C.free(unsafe.Pointer(cstr))}
The above are the 9 main features of the Go language summarized in the book. I have summarized them based on my own experiences and some summaries in the book. People who want to know the language of Go and want to enter this field can have a rough idea of Go. If you want to learn more, you can Go to the Go language programming developed by qiniu cloud storage team. I will continue to learn later.