Why do I like the Go language (Simple go language) _golang

Source: Internet
Author: User
Tags data structures exception handling

Since 2000, has also written 11 years of code, during the use of VB, Delphi, C #, C + +, Ruby, Python, has been looking for a door to their own mind and ideas of the language. I was very concerned about the feel of writing code and the efficiency of execution, so I didn't find it until go appeared. After familiar with go, although I did not stop and experience D language, but almost immediately gave up, its design is still too complex.

Let's talk about go. It's good in fact also two words-concise!

See a lot of friends of the message that these "less parentheses, less a semicolon," something like that doesn't make sense, really? The question is, why do you have to have it if you can't? Since you can play less than one character, why do you play a lot of fun? Still feel justified? It's simpler here, it's simpler, is it a lot simpler in general? The design here is simple, there is a little more concise, whether the whole is compact and efficient?

A lot of things, to the whole to experience, can feel the real strong. Without the various "seemingly useless" support in the previous syntax, how can you do the design simplicity that follows?

I firmly believe that less is more, simple is strong, can not reduce a point of the design is really good design!

Concise variable declaration and assignment

With the simplest declaration variables and assignments, the following sentence completes the declaration type to the assignment, and finally the common semicolon as the end of the statement.

var i int = 10;

It's not that simple, is it? Why should there be "var"? Why can't I deduce the variable type myself? Why do I have to add a semicolon at the end? These three questions, which I believe the designers of the go language have asked, have been targeted for improvement. To start over.

I: = 10

What do you think? ": =" is the syntax for declaring and deriving the type of sugar, the end of the semicolon also saved, because I changed the line, the compiler understood.

You can also declare and assign values to multiple variables at once.

I, J, K: = 1, 2, 3

Different types are also available.

I, J, K: = 1, 1.0, "Hello"

If you want to declare a bunch of variables, but don't assign a value at the moment? You can do that.

VAR (

I, J int s string
U, V, s = 2.0, 3.0, "bar")

The Go designer even thought that a few dozen "Var" should not!

Concise If

It's kind of interesting, isn't it? When I learn a new language, the first glance at the variable type and the declaration, the second eye will look at the logic control syntax. Now, what do you think?

Copy Code code as follows:

If I > 10 {
println ("Greater then 10")
}

Is it normal, is it simpler to have a simple if? Yes, indeed. First of all if the conditions behind the judge no one forced you to add parentheses, just two times less buttons, and what? And also! The following should be a very common if usage scenario.

Copy Code code as follows:

Result: = SomeMethod ()
If result > 0 {
}

A lot of times the variable of result is just for conditional judgment and can be thrown away after if, so go has this writing.

If result: = SomeMethod (); Result > 0 {

}

This expression is too common, really who wrote who know, every time I write a line will be a good feeling. Take a look at the tangle of the If segment.

Copy Code code as follows:

If a {
else if B {
else if C {
} else {
}

This is possible, but not go recommended, because it can be more concise. such as the powerful switch.

A powerful switch

This is a well-known switch usage, note that there is no break Oh! There is no "wear" between the cases on go.

Copy Code code as follows:

Switch Tag {
DEFAULT:S3 ()
Case 0, 1, 2, 3:S1 ()
Case 4, 5, 6, 7:S2 ()
}

Magic Little Switch, hey, and if the same as the best.

Copy Code code as follows:

Switch x: = f (); {//missing switch expression means ' true '
Case X < 0:return-x
Default:return x
}

And this, with this more specific wording, you really will if...else If...else if...else ... Do you?

Copy Code code as follows:

Switch {
Case x < Y:F1 ()
Case x < Z:f2 ()
Case x = = 4:F3 ()
}

Condition to judge comfortably, what about circulation?

Lonely for

In fact, I have not quite understand, why a language to provide a number of cyclic grammar? For, while, do...while ... are irreplaceable? Which one do you use? Looks like a hobby, right? Maybe you can just give an example to prove the existence of these three things necessary and subtle differences, but for me, to do the same thing if there are many ways in fact is the design of redundancy, will cause more or less trouble to users. Take a look at the go cycle.

Copy Code code as follows:

For I: = 0; I < 10; i++ {
}
For a < b {
}
for {
}

See, a for is going to take care of everything. Look at a commonly used traversal set, one that will be written like this.

Copy Code code as follows:

Count: = Len (Somearray)
For I: = 0; I < count; i++ {
println (Somearray[i])
}

To simplify this, go gives a keyword "range" to see the usage first.

Copy Code code as follows:

For I, Value: = Range Somearray {
I is an integral type, representing the subscript
Value is the type of the values within the array
}

Range is not only available for arrays, but it can actually be used for any set, such as map.

Copy Code code as follows:

M: = map[string]int{"Mon": 0, "Tue": 1, "Wed": 2, "Thu": 3, "Fri": 4, "sat": 5, "Sun": 6}
For I, s: = Range A {
Type of i is int
Type of S is string
}

Here are just a few of the most basic grammar scenes, go inside there are many!

function can return multiple values

In fact, there are many languages that can be assigned multiple values, but a function can return more than one value, such as in C # if you want to return two int, this is usually the case.

Copy Code code as follows:

public class Twoints
{
public int A;
public int B;
}
public class Foo
{
Public twoints returntwoint ();
}

Then you can twoints ti = foo. Does Calctwoint () feel sad? Maybe you're numb, right? Many languages are designed in this way. The problem that a function can only return one value is that it causes many unnecessary data structures to occur. The above reflects the redundancy, of course, you say you can use the Out keyword to let the function return, but this syntax is not so safe to use. And this problem is too easy to solve in go, because the function of went can return multiple values!

Copy Code code as follows:

Func returntwoint () (int, int) {
}
A, B: = Returntwoint ()

I have a good impression of go from here, which makes my library less than a lot of data structure! This can virtually reduce the complexity of the design.

Object pointers that are declared inside a function can be safely returned

Copy Code code as follows:

Func returnpointer () *object1 {
Obj: = new Object1 ()
Obj. A = "Hello"
return obj
}

Go garbage collector will handle this situation, rest assured!

Exception handling? What's defer? Can I have it?

Why is exception handling so complicated? How many people can safely implement the following logic? The following is pseudocode.

Copy Code code as follows:

File f = file.read ("C:\\text.txt")
F.write (XXX)
F.close ()

I believe that there are a variety of try...catch...finally in the brains of experienced farmers. There are all kinds of writing rules, such as "catch" where the logic can't throw out the exception. Actually think about it, our request is very simple, open a file, and then make sure it is closed at the end. That's all, why is it so complicated to do something so simple? Let's see how the Go is done!

Copy Code code as follows:

Func savesomething () {
If f, err: = OS. Open ("C:\\text.txt"); Err = = Nil {
All kinds of reading and writing
Defer F.close ()
}
}

All defer functions are executed after the current function (here is savesomething) is executed. Exception f occurs when "//all kinds of reads and writes". Close will also be determined to be executed when the savesomething exits. With this, the release of resources, the closure of a few handles such a trivial matter no matter!

The interface is no longer "implemented"

From my approach to oo thinking, all interfaces have a different way of requiring a class to "implement" the interface, which I have always considered to be justified until I met go.

Copy Code code as follows:

Type Speaker Interface {
Say ()
}

The above defines an interface, with only one method, Say, no parameters, no return value. Go, any object that has all the methods defined by an interface is implemented by default. This is a sentence with too many connotations, enough to have a significant impact on the design ideas. This method, for example, accepts a parameter of type speaker.

Copy Code code as follows:

Func saysomething (s Speaker) {
S.say ()
}

Then all the things that have say () can be thrown in.

In the go world, all things are implemented by default interface{} this interface. With this concept, even without generics can effectively reduce the complexity of the design.

Can multithreading be a little bit simpler?

To write multiple threads, you have to understand thread, know all kinds of locks, understand all kinds of signal volume. In various systems, "asynchronous" logic usually represents "difficulty". This is the strongest part of go, have you ever seen an asynchronous code that is simpler than this (the following code is excerpted from Go's official example)?

Copy Code code as follows:

Func IsReady (what string, minutes Int64) {
Time. Sleep (minutes * 60*1e9);
Fmt. Println (What, "is ready")
}
Go IsReady ("Tea", 6);
Go IsReady ("Coffee", 2);
Fmt. Println ("I ' m waiting ...");

The result of the execution is that the print:

I ' m waiting .... (Right away)
Coffee is ready (2 min later)
Tea is ready (6 min later)

The go language has a built-in "go" syntax, and any method of going will be executed asynchronously. What about passing messages before the asynchronous method? Use the channel to chant. The name is a pipe, one to write, the other to read.

Copy Code code as follows:

CH: = make (chan int)//Create a pipe that can only pass an integral type

Func pump (ch Chan int) {
For I: = 0;; i++ {ch <-i}//write value to pipeline
}

Func suck (ch chan int) {
for {fmt. Println (<-CH)}//This will wait until a value comes out of the pipe.
}

Go Pump (CH)//Asynchronous Execution pump
Go Suck (CH)//Asynchronous Execution suck

Hey, then you see a bunch of numbers on the console.

This time to write it here, do not live in the go inside the other good things, brother Hungry, on the one by one appearance, sorry sorry! Take a bow! Step!

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.