Go! Beautiful language!

Source: Internet
Author: User
Tags key string
This is a creation in Article, where the information may have evolved or changed.

This week, taking advantage of the one-hour hours from work every night, learning the Google-developed go language has a basic understanding of it. It's really a beautiful language.

First, from its design goal is to design an efficient, statically compiled, easy-to-write language. It is involved in system-level programming and is trying to contend with C + +.

In detail, its design objectives are as follows (from Wikipedia and Golang FAQ):

    • Security: Type safety and memory security. No inheritance, no handling of type dependencies, weakening of type usage, default initialization of variables, simplified design burden.
    • Support for concurrency and communication. The built-in concurrency mechanism makes multithreaded programming very simple, and the built-in Chan (channel) type simplifies communication between threads.
    • A complete memory garbage collection mechanism.
    • High-speed compilation. No header files, makefile and other complex engineering dependencies, making the compilation faster, the project easier to organize.

In my opinion, through a week of study, I left the deepest impression, is the following aspects:

    1. More in line with natural language syntax. Types of declarations are placed behind variables, and actual combat discovery is actually easier to read than to put in front.
    2. Convenient built-in type. string, map, array, and so on, these complex types are built into the language.
    3. Built-in concurrency mechanism. Support for programming multi-threaded program is very good.
    4. There are no classes, only structs, and interfaces. Just not used to it, there is no benefit of finding it.
    5. Document. From basic syntax, package documentation, to tutorials, design recommendations, and more. For understanding go, it is very helpful to write good go.

Here I will take some of the code I wrote in the tutorial, for example, to say my understanding of the above points.

The Grammar of Nature

The grammar of the go language is very much in line with the English grammar (English grammar is more logical than Chinese, and more clearly explains the problem).

Like what

Define a variable: x int, read in English is x of type int;

Define a function: Func add (x, y int) int, read it: A function named Add, with parameter X & y of type int, that returns INT. Very natural.

Of course, to show the nature of this definition, we can look at a complex example of a function pointer:

First look at the definition of the C language:

Int (*FP) (int (*FF) (int x, int y), int b)
It defines a function pointer FP, which points to a function that takes the function pointer ff and B as arguments and returns an int. Where FF points to a function that takes X, y as an argument and returns an int. X! It's complicated.

What if I use go?

FP func (FF func (x, y int) int, b int) int

Does it coincide with the description above?

This definition, which conforms to the natural language syntax, simplifies the process of code understanding and is not prone to error.

For more detailed information about this section, refer to Go's Declaration Syntax.

Here is a Hello World program, a glimpse of the fast:

Like Java, the package name is used to organize the code packages Mainimport "FMT"//program "entrance", main function. Func Main () {FMT. Println ("Hello, World")//No Return statement}


Convenient built-in type

Here I take an example of a practice in tour.golang.org, which describes the map and string in the go language.

This exercise requires:

Implement the WordCount function. This function enters an English sentence and returns a map type that stores the number of repetitions for each word. The main function is well written and contains a WC. The test function, which tests the correctness of the WordCount function.

Tip: Strings. Fields can be very helpful.

Here is my implementation:

Package Mainimport ("TOUR/WC" "strings") func WordCount (s string) Map[string]int {//Create a key string, value int map// Make can be used to create any type of variable. For example make ([]int, 3) is an int array m that creates 3 elements: = Makes (map[string]int)//variables can be used without displaying the specified type//here, the type of words is the return value type of fields, is a string array words : = Strings. Fields (s)//Go language does not have while, the do-while//for condition {execution Body} is equivalent to while//for {executing body} that is infinite loop//here, use for the range attribute, take words index and value//to _ and word respectively , the underscore _ is equivalent to a placeholder, not assigned to a specific variable//the same, you can also use: I, _: = Range words, means only its index//can even be used: _, _: = Range words, indicating that only the corresponding number of cycles can be called for _, Word: = R Ange words {//The key takes the values in the map and modifies//GO is a memory-safe language, if the word key does not exist in M//will automatically create a word and initialize its value to 0m[word]++;} return M}func Main () {WC. Test (WordCount)}

From this example, we can learn a lot about the features of the go language, such as _, Word: = Range words multiple assignments (also available for function return values), such as built-in string, map type, such as a simplified loop body (without parentheses, minus while, Do-while, support for the definition of multiple cyclic conditions), and how the code is organized.


Structs and Interfaces

The go language has no concept of class, no constructs, no destructors, and no inheritance. Only structs and interfaces.

The following is an example of Exercise:images, which describes the use of the structure and interface of the Go language:

Package Mainimport ("image" "Image/color" "tour/pic")//define image Type//similar definitions can also be: type MyInt int//equivalent to Typedeftype image struct{content [][]uint32//Two-dimensional array that stores the image content//contains RGBA values for each pixel point. width, height int//picture width and height}//a custom pixel point function, the RGBA value returned to the given point, Func valueofpointer (x, y int) UInt32 {return UInt32 (0xfffff*x^ ( 0xfffff*y + 0xff)}//custom picture generation function for generating a picture using the given pixel point function func makepic (w, H int, F func (Int,int) uint32) *image {img: = new (image ) Img.width = Wimg.height = h//Here first apply for a length of W, the type of []uint32 array img.content = make ([][]uint32, W) for x: = 0; x < W;  x + +//The element of each array is then requested for the H-length array of type uint32//resulting in a two-dimensional array of W x H img.content[x] = make ([]uint32, h)//Use the F function to assign a value for y to each pixel: = 0; y < H y++ {Img.content[x][y] = f (x, y)}}return img}//////////////////////////////////////////////The next few functions are the interface image. Image function implementation//GO language, no need to display the declaration implementation interface//only need to implement all functions of the interface, that is, the interface///Bounds function returns the usable area of the picture//between the Func and the function name plus a type, indicating that it is a member function of the type//Note, The types here are not limited to structs, such as floating-point numbers or integers. Func (img *image) Bounds () Image. Rectangle {return image. Rect (0, 0, img.width, img.height)}//ColorModel LetterNumber indicates the color mode used for the image///Here, we choose the RGBA mode func (img *image) ColorModel () color. Model {return color. The rgbamodel}//at function returns the color property of the specified pixel point, func (img *image) at (x, y int) color. Color {//Set the colors of out-of-range points according to the practice instructions if x >= img.width | | y >= img.height {return color. Rgba{uint8 (x), Uint8 (y), 0xFF, 0xff}}//generates the color of the RGBA mode and returns var c = Img.content[x][y]return Color based on the stored two-dimensional array. Rgba{uint8 ((c >>) & 0xFF), Uint8 ((c >> +) & 0xff), Uint8 ((C >> 8) & 0xff), Uint8 (C & 0x FF)}}func Main () {m: = Makepic (+, +, valueofpointer)//Call the PIC class's ShowImage to display the resulting picture pic.showimage (m)}

It may be that I have not yet understood the essence of the go language, and have not yet discovered the advantages of such a design without class or even showing an inheritance relationship. If there are friends who know must tell me, thank you very much!

Built-in concurrency mechanism

The go language has built-in concurrency mechanisms that allow easy creation of threads without the support of third-party libraries. Also, the Go language contains a Chan type for variable transfer between threads, reducing the risk of using shared memory transfer, some similar to the pipeline in UNIX.

The following is an example of a equivalent Binary trees that describes the use of concurrency and Chan, and is further familiar with the go language:

Package Mainimport ("FMT" "Tour/tree" "sort")//Walk traverse T, send all its contents by CH//I use recursion to implement IT//note that the channel of the Go language is a type of Func Walk ( T *tree. Tree, ch Chan int) {if t.left! = nil {Walk (t.left, ch)}if T.right! = nil {Walk (t.right, ch)}//use <-symbol to send variable values to Chanch &L t;-t.value}//same Determines whether T1, T2 are two trees with the same content func same (t1, T2 *tree. Tree) bool {//Create two pipes with cache//Manage send threads will be sent continuously until the cache overflows,//wait until the management received thread takes out the value before it can continue sending//This is equivalent to a fixed-size queue. CH1: = Make (chan int, x) CH2: = Make (chan int, 10)//Use two arrays to store the contents of the tree a1: = Make ([]int, x) A2: = Make ([]int, 10)//Create two threads while Start traversing go Walk (T1, ch1) go Walk (T2, CH2)//The main thread will not stop receiving data for the other two lines Cheng for i: = 0; I < 10; i++ {A1[i] = <-Ch1a2[i] = <-ch2}//sorted to make it easy to check the consistency of its contents sort. Ints (A1) sort. Ints (A2) for i: = 0; I < 10; i++ {if a1[i]! = A2[i] {return false}}return True}func main () {//tree. New (k) can create content containing K, 2k, 3k, ..., nk tree T1: = tree. New (1) T2: = tree. New (2) ch: = Make (chan int, 10)//Print T1 tree fmt. Print ("T1:") go Walk (t1, ch) for I: = 0; I < 10; i++ {fmt. Printf ("%2d,", <-ch)}fmt. PRINTLN ()//Print T2 tree FMT. PriNT ("T2:") go Walk (T2, ch) for I: = 0; I < 10; i++ {fmt. Printf ("%2d,", <-ch)}fmt. PRINTLN ()//test same function fmt.printf ("is%v that T1 equal t1.\n", Same (T1, T1)) fmt. Printf ("is%v that T1 equal t2.\n", Same (t1, T2))}

By example, you can see how the pipe is used: <-. Send can be <-value with channel, receive can be used variable: = <-channel. Very image.

Concurrency in the Go language is function-based. Using Go function () allows this function to run in a new thread, and the parent thread will continue to run without waiting for the function to end.

For more complex and flexible use of concurrency, see exercise: Web Crawler.


OK, a brief introduction to go is here, more detailed documentation can be found in the official Go language website: http://golang.org/.

The code involved in this topic (Go language Learning) has been synced to GitHub for easy sharing, and here's the link:

Https://github.com/tankery/study-go


Note: From today on, I will write this blog at least once a week.

As for the frequency of one article per week, it is determined by the nature of my working overtime. One weekly, legal holiday break ...


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.