Several interesting features in the go language and their views on go

Source: Internet
Author: User

1. multi-value return

In C/C ++, if multiple values need to be returned, the pointer or reference is usually input in the function, for example

Fun (int * a, int * B, int * C), but in go, if you want to return multiple values, you only need to write the function as follows:

 
1Func test_func ()(Int,Int,Int){2A: =1;3B: =2;4C: =3;5 6ReturnA, B, C;7}

Finally, the function returns A, B, and C in sequence.

This is actually already available in Lua, so actually nothing new in go. Go also has a feature of Returning Value naming.

 
Func read_file () (read_count int, err INT ){
....//CodeWhat needs to be done
Return;
}

In this way, the code of the function can be clearer and more understandable. You can see the function declaration to know what the return value is.

 

2. zero value initialization, automatic derivation type

C ++ 11 adds an auto, and the = symbol in go can be automatically deduced. For example, if a: = 1, A is automatically deduced to the int type, another feature is Ganoderma lucidum initialization.ProgramThis way we can write less code and initialize a variable (in most of my code, we also use 0 to initialize the variable ), if C/C ++ has this feature, many errors can be easily found. I think a lot of code is caused by no initialization.

 

3. Garbage Collection

Needless to say, this is definitely a powerful tool. Resource Management has always been a headache for C/C ++. Of course, automatic garbage collection will definitely lead to performance degradation, even memory leakage (it is said that Java will also have memory leakage issues, which are available in Python, although these all have garbage collection mechanisms)

4. slices

To put it bluntly, slices points to the underlying pointer of an array. However, unlike array, slices can increase the length when an element is added, and slices is a bit similar to a pointer. Once slices is modified, the data that slices points to will also change. Go does not degrade the array into a pointer. If you input an array, go will copy the copy of the entire array, that is, if there are 100 elements, go will copy a copy of 100 elements.

 

5: defer

Defer is the code segment that will automatically call our defer life when the function exits. This is to prevent us from forgetting to close the file handle or releasing resources. C/C ++ programmers often make mistakes.

 
1F, _ =OS. Open (file_name );2 3Defer F. Close ()

The function does not immediately execute F. Close after opening the file, but does not execute F. Close () after the function is executed ()

6: interface, custom type and Method

 1   Class  Graph  2   { 3   Public  :  4       Int  Getwidth ();  5   6       Int  Getheight ();  7   8       Virtual   Void  Draw ();  9   Private  : 10       Int  Width;  11       Int  Height;  12 }

 

 

I have never liked this method of C ++ because I put a lot of functions and data together, so that when the code is too large, it will become very confusing, in addition, because of the existence of virtual functions, memset or memcpy cannot be used directly during initialization. If a class contains hundreds of variables, We need to manually initialize them one by one, unlike in C, the data structure is a native value, which can be initialized directly by memset. In go, it will automatically help us with zero-value initialization.

Actually, if you know C ++, you should know that the above class compilers still help us to separate code generation. For example, getage () will change to getage (person & person ), in go, a class is divided into three parts: data, methods, and interfaces.

 1 Type Graph Struct  { 2 Width Int  ;  3 Height Int  ;  4   }  5   6   7 Func (G * graph) getwidth ()( Int  ){  8       Return  G. width; 9   }  10   11 Func (G * graph) getheight ()( Int  ){  12       Return  G. height;  13   }  14   15 Func (G * Graph) Draw (){  16 FMT. printf ( " Graph draw  "  );  17   }  18   19 Type graph_interface Interface  {  20   Draw ()  21   }  22   23   Func draw (G graph_interface ){  24  G. Draw ();  25 }

The interface declares an interface, which is a vptr similar to the virtual function. You can understand the type graph_interface interface as a function to be added to the virtual function table, you can use this interface to call the draw function of the input parameter. (The implementation principle of the C ++ virtual function also uses this method)

Add (G * graph) before the function declaration to bind the class data with these methods. Nothing else can be said, both public and private data or functions are case sensitive. However, in go, C ++ is different from C ++. If C ++ is private, other classes cannot access this variable or function, while go is not accessible to other files, this file is still accessible, a bit similar to the static

In fact, I guess these implementation principles of Go C ++ are similar, but they only show different syntaxes. Of course, so far I prefer go syntax, I think the design idea of Go is more in line with Linus.

"Bad programmers care about code. Good programmers care about the relationship between data structures and them ."

Git's design is actually very simple. It has a stable data structure and rich documentation descriptions. In fact, I strongly agree that code should be designed around our data structure, rather than based on others. I think this is one of the reasons for git's success [...] in my opinion, the difference between good programmers and bad programmers is that they think that code is more important or data structure is more important.

 

I want C ++ programmers to take a look at this article.Article: Http://www.aqee.net/torvalds-quote-about-good-programmer/

Separating data structures from these methods will help programmers to clarify the relationship between data structures and functions.

7. goroutine

It is said that this is the biggest "selling point" of go, and there are a lot of articles on the Internet, but Lua has had it for a long time, so I think there is nothing to boast about, it is to simulate a single-core computer in the thread to run the code segment. Of course, this saves resources and does not require thread switching.

Go func_name (). In this way, a function is run as a goroutine. Of course, routine is not concurrent, but just parallel, therefore, goroutine simulates Single-core computers in the thread to run code (the difference between concurrency and Parallelism)

Go routine is also very easy to communicate, that is, using the channel, Unix shell should be familiar with this thing, not to mention it.

 

Disadvantages of go:

1. cannot be combined with C, cannot be compiled into Lib, DLL

After reading so much, I think go is still very useful, but so far, I have not found any way to embed goC LanguageIn this example, C can only be embedded in go. I think many companies are reluctant to use go. I originally wanted to put go into a project, however, it is found that go cannot be embedded into C, nor can it be compiled into DLL.

2. Not designed for concurrency as I said on the Internet, but for improved C ++

It should be able to replace C ++ or Java, but it is estimated that it cannot replace C. If someone compares go with Erlang on the internet, I still feel that go cannot be compared with Erlang,At most, go is an improved C ++. It cannot be compared with Erlang, which is born for parallel computing.Go still follows the C/C ++ object-oriented process, while Erlang is inherently process-oriented, and everything is a process, even the thread scheduling code is self-written rather than directly encapsulating the operating system's API layer. It is said that the go thread scheduling code has only a few hundred lines, and Erlang has tens of thousands lines, here we can see the difference. Even I have always thought that Erlang can be used as an operating system independently.

3. Mandatory encoding Style

Go also has disadvantages, such as some mandatory encoding methods. If you do not use a variable, it will not give you a warning, but will give you an error that cannot be compiled, it is said that it is to increase Compilation speed, which surprised me very much, because I often need to reserve interfaces or variables in programming, which is very good for future changes, is it effective to save compilation time in such a place ?? I guess it is the go designers who want to force everyone to write good-looking code. This can be seen in a lot of options that cannot be compiled, go's mandatory requirements on the programmer's programming style make me uncomfortable... what's more, we have over 10 million lines of code in the project, and the whole project is re-edited. Is there a difference between 10 minutes and 20 minutes ?? I think most people switch out to do other things.

4. Weird syntax

VaR n int; isn't that weird ?? Anyway, I am not used to the way variables are declared. There are braces.

1If True{2//Code3}Else If False{4//Code5}Else6 {7//Code8}

 

We need to forcibly enclose braces with condition statements. Do you know whether the go designer is to be unconventional or not too lazy to write syntax analysis ?? In this case, the Code does not look nice with the braces in another line. I don't know why the programmers should be forced to write like this, but it reminds me that the indentation of Python also caused a lot of controversy... I once argued with someone on the forum.

5. Is compilation really faster than C/C ++ ??

Some people on the Internet say that the compilation speed of Go is faster than that of C and C ++. In order to increase the compilation speed, go forces programmers not to include unused variables in the code, if the import package is not used, a compilation error will be prompted, but this can really make go compilation faster than C ++ ?? C ++ has always been a nightmare for Compiler designers because of the complex syntax, but I don't think go has the concept of LIB or OBJ (I didn't find the generated temporary file, or is my generation method incorrect ??), So should we re-compile all the imported files when building a project ?? If the project is large, the Compilation speed will be faster than that of C ++ ?? If the entire project of C ++ is not re-compiled, will the go Compilation speed be more advantageous than C ++ ?? I remember someone said on the Internet that the C ++ compilation method would be slow because once a file is included 46 times, it would need to be opened 46 times, but I think this problem should also exist in go, or has it been solved ??

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.