Go Language Learning Personal small note (i)

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

When I was a student, I always felt that server-side programming was a very difficult thing to do. Teachers are just a simple one: set up a socket listening client connection, connect the client to get a map to save, and then constantly polling ... This is certainly not used in the actual work, some of the key things, such as how to deal with AH, database operations how to optimize AH, security how to guarantee Ah, these classes are not learned. I also tried to learn some of this part of the knowledge, the result is my beloved C + + pit is not shallow. I have always realized that the pointer is difficult to use where the memory of their own release, is not a very simple thing? In the attempt to server-side multi-threaded programming only to really discover the difficulties of memory management ... Many things are different under multi-threading, and I have always thought that the correct destructor is suddenly incorrect. And it often takes a lot of third-party libraries. I don't know how to write a third-party library, and the author of the third-party library doesn't know if I'm going to use it as he wants. The result is memory error can not be avoided, the wild hands flying in the sky. Of course, I believe that as long as the patient seriously study, these problems in C + + also can be solved. Only because after graduating their own work has become a hand-tour client development, there is not so much time to understand these.

Recent work is not very good, a lot of messy things. So I decided to look at the server-side programming. After working in contact with a lot of language, only to know that in other languages to develop a server side is not so difficult to believe in the past. The company's server big God is using Java, I looked at a bit of thought is not so complicated. Moreover, most of the online games on the mobile phone are weak networking types, with some web frameworks are enough, some time ago I used Django experiment, I feel this way is really simple. But Django itself is a Web development framework, not a Web server, or a deployment to Apache or Nginx. So I spent more time in setting up a variety of environments than I was writing code.

Today, I'm going to study the language of Go, which was launched by google2009 year. It is said to deal with multithreading has unique. Frankly speaking, I hated her after a simple look at the grammar. For example, the go rule defines a function when the first curly brace cannot be written to the next line on another line. This is really exaggerated, because my habits have always been written to the next line, and no language said you have to write in this line, otherwise you can not compile ... You might say that a mere curly brace of words can be a reason to hate a language, but the history will reveal that Catholics and Muslims have fought for more than 1000 of years with God, who we atheists believe does not exist. Programming language is like a woman, the key to your liking for her is the way it looks. As far as you say Windows application Programming C # First Ah, Erlang processing multithreading powerful Ah, LUA and C + + writing game speed Ah, these are you in some areas to choose her reason, the equivalent of a woman's inner, but also you finally to choose and a woman to marry the reason, but does not necessarily mean that you like her. It's as if curly braces can't be written to the next line, I hate the Go language right now, but I choose to use it to write a server.

So let me begin by understanding its variable type, function declaration, selection and loop of these basics.

Let me first try to write a small thing that uses Newton's iterative method to find the square root:

 PackageMainImport("FMT""Math")funcMain(){varHellostr ="Hello, go.\n."       Fmt.Print(HELLOSTR) Tipstr: ="Please enter a positive number for me to ask for its square root:\ n "       Fmt.Print(TIPSTR)varClacnumfloat64//If you write onlyvar clacnum,do not explicitly specify the type to error       offClacnum <0{FMT.Print("you're teasing me, negative numbers don't have square roots.\ n ")       }else ifClacnum = =0{FMT.Print("0the square root is still0\n ")       }Else{FMT.Printf("%gthe square root is:%g\n ", Clacnum, newtonsqrt(Clacnum)) }}funcnewtonsqrt(xfloat64) (iguessfloat64){//Newton iterative method for square root, just to learn the loop       Iguess =1        forMath.Abs(iguess * iguess-x) >1e-12{//with thefor ; math. Abs (iguess * iguess-x) > 1e-12; {}same              Iguess = (iguess + x/iguess)/2       }return}

First, there are several ways to declare variables in the Go language: The first is var hellostr = "Hello, go.\n", which does not require a declaration type, and the initial value determines the type of the variable. The second type is like tipstr: = "", which is equivalent to the above one. The third is the non-assignable, like Var clacnum float64, which is worth declaring. Float64 is one of the basic types of go, nothing to say. It is important to note that the go language declared variables must be used at least once, otherwise the compilation will error. To be honest, although this requirement is a very helpful to the requirements of the programming specification, but just write down the variables of the IDE in the following line to draw a hint you "unused" feeling very uncomfortable there is no!

Next is the normal IF...ELSE selection structure, curly braces can not be written on another line, and even else if the other line must be curly braces on the same line, simply. Go is a nasty guy.

The following is a function called Newtonsqrt, where the first parenthesis is the parameter list followed by the return value. In the end I did not write return iguess, because at the time of declaration it was declared that iguess is the return value. Of course it can be written in the following form:

Func newtonsqrt (x float64) float64{//Newton iterative method for square root, just to learn a loop var iguess float64 = 1for Math. Abs (iguess * iguess-x) > 1e-12{//with for; math. Abs (iguess * iguess-x) > 1e-12; {} Same iguess = (iguess + x/iguess)/2}return iguess}

The function is to use Newton iterative method to find the square root of the loop, for math. Abs (iguess * iguess-x) > 1e-12 It looks a bit strange, why is it for instead of while? There is no while in the go language, this for actually omits two semicolons, equivalent to For;math. Abs (iguess * iguess-x) > 1e-12;. This looks just like C + +.

Run it and try it:


It seems to end here, but if the naughty people do not enter the numbers but enter some strange string to come in?


The program did not crash, but obviously we should not let that happen. If it is a different language, you will certainly say Try...catch ..., but the go language is not try...catch. Actually FMT. scanf This method has a return value, and it is 2. Strangely, a function has two return values. In fact, if it's a person who learns to go as the first programming language, you ask him how it feels to return two values to a function, and he's definitely not going to answer the odd question. To be honest, when I was a beginner of C, I was able to return only one value to a function. Why can't I just return two values? Define a structure or a variable pointer into it, how to think it is not convenient. Of course, familiar with C or Java after the person, naturally feel that the return of two value is strange. In other major programming languages, LUA and the swift function of Apple can also return multiple values.

Func Scanf (format string, a ... interface{}) (n int, err error) {return Fscanf (OS). Stdin, format, a ...)}

In front of the int will not say, after the err to see what is done. This changes the code to the following:

 PackageMainImport("FMT""Math")funcMain(){varHellostr ="Hello, go.\n."       Fmt.Print(HELLOSTR) Tipstr: ="Please enter a positive number for me to ask for its square root:\ n "       Fmt.Print(TIPSTR)varClacnumfloat64//If you write onlyvar clacnum,do not explicitly specify the type to error       _, ERR: = FMT.Scanf("%g", &clacnum)//_used for placeholders, ignoring unwanted return values       ifErr! =Nil{FMT.Print("Don't enter strange things in random! ")return       }ifClacnum <0{FMT.Print("you're teasing me, negative numbers don't have square roots.\ n ")       }else ifClacnum = =0{FMT.Print("0the square root is still0\n ")       }Else{FMT.Printf("%gthe square root is:%g\n ", Clacnum, newtonsqrt(Clacnum)) }}funcnewtonsqrt(xfloat64) (iguessfloat64){//Newton iterative method for square root, just to learn the loop       Iguess =1        forMath.Abs(iguess * iguess-x) >1e-12{//with thefor ; math. Abs (iguess * iguess-x) > 1e-12; {}same              Iguess = (iguess + x/iguess)/2       }return}

When you receive multiple return values, you can use the underscore _ to take a bit, ignoring some of the return values, where I ignore the return value of the first int type of scanf. Then determine if err is empty (nil).

Run again and try to enter something strange:


In the Go language, this process is the recommended way for the designers of go. Of course there is another exception that is similar to Try...catch: defer, panic, recover, but go designers do not seem to recommend it, because mixing exceptions with control structures can easily make the code confusing, and they pursue simplicity and elegance ... Well, after all, it's a bunch of pagans who don't let people write curly braces on the next line, so they don't bother to recommend it. The
is going to be a good place to study today.

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.