This is a creation in Article, where the information may have evolved or changed.
Go Language Introduction
The Go Language (Golang) is a new programming language introduced by Google to reduce the complexity of your code without compromising application performance. Rob Pike, Google's Chief software engineer, said: "We're developing go because software development has been frustrating over the last more than 10 years."
The main features of the Go language:
- Compiled language, execution efficiency close to C + +
- Automatic garbage collection
- Richer built-in type and automatic type deduction (similar to c++11 Auto)
- function can return multiple values
- Have better error handling
- Anonymous functions and closures
- Support Types and Interfaces
- Concurrent programming
- Support reflection mechanism
- Strong language interactivity
- Automatic derivation of engineering dependency
- Easy to package and deploy
- ......
Personally, I feel that the go language is a fix and an extension to the C language. The language that was designed by a group of engineers was just too good for my taste, and all the features were meant to solve real problems. But the new features don't add a burden to the language, but the syntax of Go is simple. Boulevard to Jane, that's why I like go.
Go language Development environment deployment
This is believed to be easy to get to download and install the tutorial online, do not repeat it.
Introduction to the basic grammar of Go language
First look at a go language version of the "Hello World" program:
package main // 声明本文件的包名是mainimport "fmt" // 导入fmt包 func main() { // 入口函数 fmt.Println("Hello, Go语言!")
The results are output after compiling the run with Go run hello.go. The default encoding in the Go language is UTF-8, so it's natural to support Chinese.
The first feeling looks like go is the Java or Python and C language hybridization it? The package and import are really similar to what is meant in Java or Python. The go language does not continue to carry the heavy burden of C-language header files, but uses a better mechanism.
This is the prototype of the main function, with no parameters and return values, and the command-line arguments are passed using other mechanisms. Interestingly, the opening parenthesis after main () {is not available for another row. This is only a personal habit in C language, but in the go language is a hard rule, written in the following words is directly a compiler error.
The line at the end of the printed statement can have no semicolon, and the compiler will automatically add it. Because support can not write a semicolon, so the go language does not allow the left parenthesis to another line, or the compiler will not know whether the end of the line should be a semicolon.
Declaration and initialization of variables
The go language introduces the var keyword to define the variable, and the biggest difference in C is that the type of the variable is written behind the variable. Here are a few examples:
var i int = 5 // 定义了一个整型变量i=5var str string = "Go语言" // 对,string是内置类型var pInt *int = &i // 没错,指针var array [10]int // 有10个元素的数组var ArrayPart []int // 数组切片,很python吧var Info struct { // 结构体,和c语言的没啥太大区别 name string
Even the inventors of the go language think it's bad to write a few more Var:
var ( a int = 1 b int = 2
Still a little bit of trouble? Then you can do the same:
I will be created and initialized to 10, and the type will be automatically deduced as int; the same is true for STR, which is deduced as a string type and initialized.
And even more, exchange variables in C are required for an intermediate variable, but the go language is not required! Just like this:
array[i], array[j] = array[j], array[i]
So the two variables are exchanged, is it simple?
There are a lot of built-in types for the go language, and here are some simple lists:
- Boolean type bool
- Integral type int8 byte int16 int uint int32 int64 uintptr ...
- Floating-point type float32 float64
- Character Type Rune
- Strings string
- Plural type complex64 complex128
- Wrong type error
There are several composite types:
- Pointer pointer
- Arrays Array
- Array slicing slice
- Dictionary map
- struct struct (seemingly no union in C language)
- Channel Chan
- Interface interface
Type is no longer mentioned, please refer to the Go Language documentation or other materials (the sample code in go documentation is really too small ...).
Constant definition
Use the const keyword as the C language to define constants:
const PI float64 = 3.141592653
However, the go language constants can be non-writable, that is, untyped constants are supported.
The go language defines constants such as true, false, and so on, which I believe you understand.
# # #流程控制
The process control of the go language is very similar to the C language, in fact, the choice and the structure of the loop.
Let's take a look at the selection, similar to the C language:
if condition { // ...} else {
The only thing to be aware of is the position of the opening parenthesis, the left parenthesis in the other line but the compilation of the Oh ~go language limits the code style on a grammatical level, and I like the idea that ...
The only difference from the C language is that the condition after the if is not enclosed in parentheses.
Then the switch statement, the difference between this and the C language is a bit large:
i := 2switch i { case 1: // ... // 不需要break,Go语言的case不会下穿的。 case 2: // ...} // case还可以是字符串:str := "hello"switch str { case "hello": // ... case "world": // ... default: // ...} // 甚至switch都可以取代if-else if 结构了:i := 5switch { case i > 0 && i < 10: fmt.Println("> 0 && < 10") case i > 10: fmt.Println("> 10") default:
What if you want the function of the C language to wear? It's easy to write Fallthrough in the post-case statement (the test that skips the next story executes its code directly).
Then there is the loop, and the Go language loop is only for a keyword, without the C language while and Do-while. But the go language for is very flexible, there are several ways of writing:
// 接近c的写法:for i := 0; i < 5; i++ { fmt.Println("i =" , i) // Go语言打印函数的各种写法都很好玩哦} // 类似c语言while的写法:i := 0for i < 5 { fmt.Println("i =" , i) i++} // 死循环的写法,是不是很清爽呢?i := 0for { if i < 5 { fmt.Println("i =" , i) i++ } else { break
This is the most basic usage, the location of this article is a concise tutorial, the use of range please refer to other information.
function definition
Because the Go language type is to be written in the back, the definition of the function is quite different.
The definition function uses the FUNC keyword:
func Add(a int, b int) int { // 注意返回值类型写的位置 return a + b} // 还可以写成这样func Add(a, b int) int { // Go的编译器知道a,b都是int类型 return a + b} // 有意思的是Go语言的函数可以返回多个值(返回值可以有名字,error是内置的错误类型)func Add(a, b int) (ret int, err error) { if a + b > 10000 { // 假设一个错误条件,不要在意这个傻逼条件... err = error.New("Too big number...") } return a + b, nil
How does a function call? Because of the concept of the package, so the function of the inside of the package directly call on the line (function definition position does not matter, no longer the C language must be declared before the call).
sum, err := Add(10, 20)if err == nil { // ok, sum is right...}
Not in a package, you have to import the package first, and then call the function before the time to add a package name and a decimal point, like calling the Println function in the FMT package. It is important to note that if a function or variable is visible outside the package, the first letter must be capitalized (The Go language also uses syntax to constrain the code format ...).
Indefinite parameters, anonymous functions, and closures are not covered.
Error handling
The above has been a simple demonstration of the error-handling method, because the go language of multiple return value support, error handling code can write very beautiful. More advanced error handling is beyond the scope of this article, please check the information yourself. Although it is said, but I still can't help but want to briefly introduce the defer mechanism, the example is as follows (this example comes from the document):
func CopyFile(dstName, srcName string) (written int64, err error) { src, err := os.Open(srcName) if err != nil { return } defer src.Close() dst, err := os.Create(dstName) if err != nil { return } defer dst.Close()
What did defer do? Simply put, when you leave this function, the operation behind the defer is executed. In this case, such as the critical area of the code lock, through the defer statement, you do not have to worry about the critical section return when there is no forgetting to write the unlock operation, just need to use defer in the function to write the unlock operation on it. Note: There can be more than one defer statement, and the function after Feder is executed in a last-in, first-out (LIFO) line.
Object-oriented mechanism
Basic object-oriented features
In contrast to C + +, first there is no hidden this pointer in the go language, and there is no such constructor or fictional function as C + +.
The so-called no hidden this pointer means that the "this pointer" is explicitly declared and passed. While the structure of Go language has the same status as other language classes, the object-oriented mechanism of Go language abandons the many features of other so-called object-oriented languages, and retains only the basic features of the composition.
I don't want to discuss the pros and cons of the go Language object-oriented feature here, because it's easy to spark a war of words. But I still show my attitude, I support the go language approach, the core of object-oriented is message passing, not "constructing class inheritance tree".
The following is a simple example of a go structure and how to define a method on a struct (c + + programmers might prefer the term "member function", but remember that there are no classes in go, only struct types):
type Circle struct { r float64} func (c *Circle) Area() float64 {
The type is somewhat similar to the meaning of a typedef in C language. The key is the following function, which is believed to be the declaration of the function name, you have understood the syntax of the member function of the Go Language definition structure. Here I pass in the pointer type of circle, the parameter is called C (of course, here the parameter name is arbitrary). The incoming type is not necessarily a pointer type, but it can also pass in a value type (the compiler recognizes it itself).
The go language also has no keys such as public and private, and is directly determined by the first letter of the function. A function that starts with an uppercase letter can be accessed outside of the package (note that the function outside of the package is not a struct, and that the lower-case functions can also be called by other functions within the package!). This is another example of a go language that uses syntax formatting to indicate semantics, and does not know if doing so is good or bad (at least the internal code style of the project is unified ...).
The go language does not have a C + + constructor, but it also provides another way to initialize the struct type: a global creation function named new with the type name appended to it. For example, the "constructor" of the circle in the above structure is as follows:
1func NewCircle(r float64) *Circle {
How do I define an object and invoke it? The methods are defined as follows:
It has not been emphasized that all variables in the go language are initialized to 0 by default, so if you call Getarea functions on C1, C2, C3, C4, the result is 0,0,12.56,12.56
It's a bit of a problem to say that the go language doesn't support inheritance, but that the go language actually provides "inheritance", but is provided in a "combination" of grammars:
type Father struct { Name string} func (fath *Father) PrintClassName() { fmt.Println("Father")} type Child struct { Father
In this case, if the child struct has no rewrite/overwrite printclassname function, the object that defines the child struct after child executes child.printclassname () output is "Father" if the following code is added to the output is " Chlild ":
func (ch *Child) PrintClassName() {
This can also be combined:
type Child struct { *Father
If you do this, you need an external father struct object pointer when initializing the object of the child struct.
Interface
The concept of interface is not unfamiliar to people familiar with Java, and the virtual base class in C + + is similar to this concept. But the go language here interface is non-intrusive interface, do not need to inherit from this interface (remember, go does not have the usual meaning of "inheritance")
In the Go language, the interface is assumed to be implemented as long as all the functions required by the interface are implemented on a struct. So in the go language, there is no inheritance tree. As for the reason why go uses non-intrusive interfaces, this is beyond the scope of this article, please refer to the blog post published by the Go designer.
Here is an interface definition (from):
type IFile interface { Open(filename string) (pfile *File, err error) Close() error Read(buf []byte) (n int, err error) Write(buf []byte) (n int, err error)} type IReader interface { Read(buf []byte) (n int, err error)} type IWriter interface {
At this point, if there is a struct textfile implementation of the open,close,read,write of the four functions. You do not need to inherit from these interfaces, you can assign values, for example:
An empty interface, interface{}, is any type that can point to any type.
interface query, type query and other features further study see the Go language documentation.