Why I like the Go language

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

Why I like the Go language

From 2000 to present, also wrote 11 years of code, during the use of VB, Delphi, C #, C + +, Ruby, Python, has been looking for a consistent with their own mind and philosophy of the language. I really care about the feel and the efficiency of the execution when I write the code, so I never found it before go appeared. After I was familiar with go, I did not stop, but also experienced d, but almost immediately gave up, its design is too complex.

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

See a lot of friends of the message that these "less parentheses, less a semicolon" and the like things have no meaning, really? The question is, since we can not, why do we have to? Since you can play less than one character, why is it very happy to play? Still feel justified? Here's a little simpler, there's a little bit simpler, is it a lot simpler in general? The design here is simple, there is a simple, is the overall compact and efficient?

A lot of things, to realize the whole, to feel really strong. Without the various "seemingly useless" support in the preceding syntax, how can you do the design simplicity mentioned later?

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

Concise variable declaration and assignment

With the simplest declaration variable and assignment, 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 concise, is it? Why do we have to have "var"? Why can't I deduce the variable type myself? Why do I have to add a semicolon to the end? These three questions, I believe the go language designers have also asked, and have targeted to improve. Re-come.

I: = 10

What do you think? ": =" is the syntactic sugar that declares and infers the type, and the end of the semicolon is also saved, because here I'm changing the line, the compiler understands.

You can also declare and assign 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 temporarily do not assign a value? You can do that.

VAR (

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

)

Go designers even think more dozen "var" should not!

A Concise if

It's kind of interesting, right? When I learn a new language, I look at the variable types and declarations at the first glance, and the second eye looks at the logical control syntax. What do you see now?

If I > 10 {

println ("Greater then 10")

}

Is it easy to be a simple if? Well, yes, indeed. First of all, if the condition behind the If no one force you to add parentheses, just a few two times the button, and what? And also! The following should be a very common if usage scenario.

Result: = SomeMethod ()

If result > 0 {

}

Many times the result of this variable is actually used only for conditional judgment, and can be thrown away after if, so go has this notation.

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

}

This expression is too common, who writes who knows, every time I write a line will be a good heart. Take a look at the tangled if segment.

If a {

} else if B {

} else if C {

} else {

}

This is a good way to do it, but not recommended for go, because it can be more concise. Like a tough switch.

A powerful switch

This is a well-known switch usage, note that there is no break Oh! Go inside case does not "wear".

Switch Tag {    
        S3 () Case    0, 1, 2, 3:
        S1 ()    
        S2 ()}
The magic of Switch, hehe, and if similar to the wonderful.
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 ... It?

Switch {case    x < Y:F1 () Case x    < Z:F2 () case    x = = 4:f3 ()}

Condition judgment Comfortable, circulation?

Lonely for

In fact, I always do not understand why a language inside to provide multiple loop syntax? For, while, do...while ... are irreplaceable? Which one does it use? Looks like a hobby, right? Maybe you can give an example to prove that these three things exist in the necessary and subtle differences, but for me, to do the same thing if there are many ways in fact is design redundancy, will cause more or less trouble to users. Let's take a look at the go loop.

For I: = 0; I < 10; i++ {

}

For a < b {

}

for {

}

Look, a for is going to get all the things done. Take a look at a commonly used traversal set, one that will be written like this.

Count: = Len (Somearray)

For I: = 0; I < count; i++ {

println (Somearray[i])

}

To simplify this, go gives a keyword, "range," which looks at usage first.

For I, Value: = Range Somearray {

I is integral type, representing subscript

Value is the type of the values within the array

}

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

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 I s 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 in a row, but a function can return more than one value, such as in C # if you want to return two int, you usually do.

public class Twoints

{

public int A;

public int B;

}

public class Foo

{

Public twoints returntwoint ();

}

Then you can twoints ti = foo. Calctwoint () Feeling sad and hurried? 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 a lot of unnecessary data structures to occur. The above shows this 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 go can return multiple values!

Func returntwoint () (int, int) {

}

A, B: = Returntwoint ()

I am fond of go is from here sprout, this let my library inside from then a lot less data structure! This can virtually reduce the complexity of the design.

The object pointers declared inside the function can be safely returned

Func returnpointer () *object1 {

Obj: = new Object1 ()

Obj. A = "Hello"

return obj

}

Go's garbage collector will handle this situation, rest assured!

Exception handling? What's defer? Can you eat it?

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

File f = file.read ("C:\\text.txt")

F.write (XXX)

F.close ()

I believe that experienced yards of farmers in the brain instantly appeared in various versions of the try...catch...finally ..., there are a variety of writing standards, such as "catch" inside the logic can not be thrown out of the things like. 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? See how the GO is done!

Func savesomething () {

If f, err: = OS. Open ("C:\\text.txt"); Err = = Nil {

Various reading and writing

Defer F.close ()

}

}

Any function that adds defer will be executed after the current function (this is savesomething) is completed. Exception f when "//various reads and writes" occurs. Close is also determined to be executed when the savesomething exits. With this, releasing a resource, closing a handle is no longer a trivial matter!

The interface is no longer "implemented".

From my exposure to OO ideas, all the languages that have interfaces require the class to "implement" the interface in different ways, which I have always thought was justified until I met go.

Type Speaker Interface {

Say ()

}

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

Func saysomething (s Speaker) {

S.say ()

}

Then everything that has the say () method can be thrown in.

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

Can multithreading still be simpler?

To write multi-threading, you have to understand thread, understand all kinds of locks, understand a variety of signal volume. In various systems, "asynchronous" logic usually represents "difficulty". This is the most powerful part of go, have you ever seen a simpler asynchronous code than this (the following code is excerpted from the official example of Go)?

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

The result of the execution is that printing:
I ' m waiting .... (Right away)
Coffee is ready (2 min later)
Tea is ready (6 min later)

The go language has a "go" syntax built into it, and any go method will be executed asynchronously. What about the Async method before passing the message? Use the channel to chant. The meaning of the name is a pipe, one to write, the other to read.

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

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

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, and then you see the console output a bunch of numbers.

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.