Go Get started tutorial for Ruby programmers

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

Those in Google have developed a language called Go's bull fork. At first glance, Ruby and go are a bit like a distant cousin. In fact, their complementary functions make them a perfect combination.

It's good for Ruby programmers to take the time to learn about go, because some of the innovations in the go language are good.

For me, go makes up for the gap between C + + and Ruby. In particular, I usually choose c + + when I need to implement a highly responsive server, but I lose the finer point of Ruby. Although I prefer Ruby, even recently, when there is a noticeable improvement in performance, Ruby can't cope.

Go makes up for this vacancy. It provides a sense of dynamic language like Ruby and Python, while also providing the performance of the compiled language.

Go also has some unique features that are described in detail in this article. OK, let's have a good look.

Mitisky
Translated 10 months ago

3 Person Top

top translation of good Oh!

Where's go?

When writing a server, one way to implement concurrency is to open a thread for each client (you might think it's nonsense, OK!). It doesn't matter, read on), especially when there are many clients, this way is very bad. A better solution would be to choose non-blocking IO (which you would certainly agree). However, even if all UNIX-system operating systems (such as Linux,mac OS X, etc.), the mechanism of effectively handling non-blocking IO is different. In addition, in addition to these numerous mixed, there is a C language. I am not opposed to embedded devices using C language, because that is definitely the speed first, development time second. However, as a daily language, C has not been able to meet my needs.

Go provides amazing concurrency primitives (primitives), good syntax, excellent library of functions and fast compilers. It solves the problem I encountered in using C, to a certain extent, C + +. The go language is easy to use even when the underlying code becomes very large.

In this article, I'll take a quick look at the basic features of the Go language, based on the documentation. Our focus is on highlighting the innovations that make the go language unique.

Mitisky
Translated 10 months ago

2 Person top

top translation of good Oh!

A boring basic introduction

The go language is easy to get started with and there is nothing to play with in basic grammar. Here are some basic code:

Package main Func main () {}
Let's start with the main function. Well, try outputting a "Hello,world"!
Package main import "FMT" Func Main () {  fmt. Println ("Hello, world!")}

The input and output modules in the Go language are called "FMT" and unlike Ruby, this "FMT" is not included by default. So it needs to be introduced at the beginning of the file with an "import" declaration. The println function in the FMT module outputs the string you passed in with a newline character (similar to Ruby's puts function). Note that the public method in the go language starts with a capital letter .

Let's look at a simple loop:

Package main import "FMT" Func Main () {  //the basic to loop for  i:=1; i <; i++ {    fmt. Println (i)  }}
For a For loop, the go language is completely different from Ruby. The For loop of the go language is a bit more or less like the C language. You need to define a variable first, then check the status, and finally explain what needs to be done after the iteration is finished (this example is I increment). The basic loop syntax in the go language is only this one. Fortunately, this for loop is very flexible. For example, the following cycle of death:
for {}

I'd like you to check out some documents with a for [http://golang.org/doc/effective_go.html#for].

Mitisky
Translated 10 months ago

2 Person top

top translation of good Oh!

Note that in our For loop above, we do not use "=" when assigning a value to the variable I, but instead use ": =". Here is an example of the difference:

package main import "FMT" Func Main () {// Defines the variable A: = 5 fmt. Println (a)//sets a different value to a A = ten fmt. Println (a)//another-Define a variable var b int b = FMT. Println (b)} 

is initialized at the beginning of the main function with the declaration of variable A, so use ": =". The following is a simple assignment, so use "=". The reason for this is that the go language is actually a static type language, unlike a dynamic type like Ruby. So the compiler has to know where this variable is declared and where it is assigned. The last part of the code is quite clear, simply declaring the variable with the var keyword and then assigning the value.

Finally, as a similar point to the array in Ruby, the array in the go language also has shards. The following code has a []type type, which means the type you want the Shard to return. But this kind of practice is a bit twisted:

package main func main {///this creates a s Lice of integers with length myslice: = Make ([]int, +)} 

We need the make () function to get a shard.

If this continues, the article may become a concise tutorial of Go language grammar. And I prefer to spend time on some interesting new features rather than a syntax introduction. The basic syntax can refer to the Go Language documentation, which will be better described.

Let's take a look at goroutines.

Mitisky
Translated 10 months ago

2 Person top

top translation of good Oh!

Goroutines

It is difficult to write concurrency code, and it is more difficult to write code that accesses the network concurrently. The problem is that traditional threads do not scale well, and once the threads are running, it is difficult to control them. The Go Language project team began to solve the problem, and Goroutine was born.

Essentially, Goroutines is a lightweight concurrency mechanism that interacts between threads by using a build called channels. They are very easy to use:

Package main import ' FMT ' func Wait () {  //wait around with a forever loop for  {  }} Func main () {  go Wait ()}  FMT. Println ("We didn ' t wait because it was called as a goroutine!")}

In the above code, the Wait method is a dead loop, but we call it through go wait () rather than directly through wait (). This is to tell go that we want to invoke it in a goroutine way and run asynchronously at the same time. Since this loop is running in the background, running the program will not clog up because of a dead loop.

So, go supports concurrency from the language itself. That is, there are concurrent primitives (Primitives)in the Go language. What is the point of this? It doesn't seem like a great move just because it's not a library or a module to implement concurrency. However, actually goroutine is fundamentally different from threads. The goroutine is lighter and more lightweight. Remember that in the server, we shouldn't create a thread for each client? However, with Goroutine, the situation is different:

Package main import (  "FMT"  "NET")//notice the arguments, the name of//the variable comes first and then COM Es the//type of the variable, just like in "Var"//declarationsfunc manageclient (conn net. Conn) {  Conn. Write ([]byte ("hi!"))  Conn. Close ()  //do something with the client} func main () {  //we is creating a server she that listens  //on Port 13 Notice that, similar to Ruby,  //a method can has a return values (although  //in Ruby, this would is an ARRA Y instead)  listener, err: = Net. Listen ("TCP", ": 1337") for  {    //accept a connection    connection, _: = Listener. Accept ()    go manageclient (Connection)  }}

Oh, wait a while! The code seems a little bit complicated, though the idea is simple. All right, let's take it one step at a time.

Mitisky
translated 10 months ago

3 human top

top   translation is good Oh!

First, let's take a look at the main function. NET was called at the beginning of the main function . Listen method, the method returns two values, one for the server connection and the other for the error message. Then, go to the main loop section of the service, where the program calls server. Accept the method, and then wait for the request. After the method is called, the program is suspended until there is a connection to the client that appears. Once a connection occurs, we pass the connection object to the Manageclient method, and the main program continues to wait for the next client connection request because the manageclient is called by Goroutine.

Finally, about this manageclient method to notice. First, note the parameter table, which is the name of the variable, preceded by the type. How much of this format is determined by the Go language creator. You may not even notice a week later.

In the method body, write to the client "hi!

Well, with just a few lines of code, we've easily completed a basic server. You can change it to an HTTP proxy (which is even better if you add a cache). Goroutines support us in doing so. In fact, Goroutine is not just a lightweight thread, because there are many different mechanisms behind it, so you can implement the goroutine function with such concise code.

Mitisky
translated 10 months ago

2 Human Top

top   Good translation!

Channels

Although, only goroutines has been very useful, but if the channels concept of support, then Goroutines will be more powerful. Channels is a communication mechanism between goroutine or goroutine and the main process. Let's look at a simple example.

Package main import (  "FMT") var eventchannel chan int = make (chan int) func SayHello () {  fmt. Println ("Hello, world!")   Pass a message through the Eventchannel  //it doesn ' t matter *what* we actually send across  Eventchannel <-1  } func Main () {   //run a goroutine that says Hello  go SayHello ()   //read the Eventchannel  //this call blocks So it waits until SayHello ()  //is done  <-Eventchannel}

The program has a call to the Sayhellothat method of the Goroutine, the method output "Hello, World" message. But pay attention to the Eventchannel statement. In essence, we declare an integral type of channel. We can send the data through this channel, while the rest can read the data from the channel. This makes channel a means of communication. In the SayHello method, Eventchannel < 1 joins the integer 1 to Eventchannel, and in the main function, we can read the data from the Eventchannel.

One thing is important here: By default, if there is no data in the channel, the read data from the channel is blocked and blocked until the data can be read from the channel.

Mitisky
Translated 10 months ago

2 Person top

top translation of good Oh!

comes in slightly more complex:

 

We have completed a main event poll, which will always be in the listening event state, which is the Loggingloop function. It receives a message from Loggchanne and then loses to the screen. This is a very general piece of design, especially in event polling to get some status.

So, with just a few lines of code, we've completed a communication between the main function and the goroutines. Because of the way of communication of shared memory, there are problems such as mutual exclusion lock, race condition and so on, which has already become the nightmare of developers. But in go, the concept of channels solves most traditional problems. In addition, the channels of Go is an intrinsic part of the language, not attached to a library.

Compared to Ruby, Go's goroutines is actually running in the background, and is implemented by the language itself (MRI Ruby runs all over a single thread, so it doesn't provide a real parallel). In addition, Ruby comes with threading implementations, but that's not really good to use. In fact, the agent library is trying to introduce some of the goroutines subtle places into Ruby.

Mitisky
Translated 10 months ago

2 Person top

top translation of good Oh!

(temporary)

In this article we have already talked about a lot of things, first introduced some very basic grammar, and then directly introduced the go language concurrency mechanism.

Please continue to follow the 2nd part, where we will be exposed to some of the complex syntax, and some other go language brings us the characteristics of the fork.



Mitisky
Translated 10 months ago

2 Person top

top translation of good Oh!

All translations in this article are for learning and communication purposes only, please be sure to indicate the translator, source, and link to this article.
Our translation work in accordance with the CC agreement, if our work has violated your rights and interests, please contact us promptly

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.