Go Language Primer

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

The programming language go used by Google System has grown more and more mature and easy to use in recent years. Now we can make the go language programming easier by using Liteide. (Note: This article should be just the first part of a series by the title and end of this article.) This section focuses on the language base, so there may be some discrepancy with the headline. )

The first step of language basics

data, types, functions, controls

The go language is an easy-to-start programming language that is incredibly powerful. You can see it as a modern version of C, and for more things, you need to find out for yourself. The go language has a clear and concise structure of static syntax, but it does represent a dynamic effect. It can also compile cost code, but it works like an explanatory language.

In general, the go language is an entirely worthwhile language to try, and this article will show you all the knowledge you need to get started with the language. In the second part, we will focus on how the go language handles objects and concurrency.

!
Loading ...

installation  

Install and configure the Go language, you only need to download the appropriate binary files to the correct location, It would be nice to locate the directory path where the files are located for the Go tool.  

If you are using OSX or the Windows operating system, you can use the installation package to do some of these columns.

Under Windows, I recommend the MSI installation package, which is still in the experiment, but it's doing very well and it can do the configuration work for you quickly.   all you need is to download the 32-bit or 64-bit installation package based on your system and then run it on your computer. The

Setup program installs by default in the C:\Go directory.

You can verify that the environment is complete by using the following applet:

Package main
Import "FMT"
Func Main () {
 fmt. Printf ("Hello, world\n")
}

You can use Notepad or another text editor to edit the above code and save the code as a hello.go file. Then open the terminal, enter:

Go run hello.go

Next you can install the liteide and try to run the program.

     

In any case, liteide is not the necessary tool for writing go programs, all you need is an editor. That's true, but for a newcomer, a good IDE can make it easier for him to get started with a language and quickly put into development.

In the ointment, Liteide did not use the manual.

You can download the tar or zip package from the URL below

https://code.google.com/p/golangide/

After the download is complete, unzip it to the appropriate directory. If you are using Windows, then you may need to use 7z to decompress.

This simple installation process will certainly not create a shortcut for you, so you may need to open ... \liteide\bin then find the Liteide.exe and manually create the shortcut.

After opening liteide you will see the Welcome screen:

Now we don't have to ignore these components, let's start with a simple applet.

Select File->new on the toolbar or click the New button directly on the Welcome screen and select Go1 Command Project in the popup dialog box. Liteide will create a Go console project for you, and the project directory is under C:/GO/SRC. If you name hello for your project, your code file will be placed under C:/go/src/hello.

Liteide will create main.go and Doc.go files in advance for you in the project directory. The following content is included in the Main.go file:

Hello Project Main.go
Package Main
Import (
"FMT"
)
Func Main () {
Fmt. Println ("Hello world!")
}

You can run the code by clicking the Blue Compile Execution button on the toolbar. You can find more commands on compiling and executing code in the B and BR button menus in the Build menu.

If you run your program, you can see the results of the program running in the build Output window at the bottom.

If the program is not running, it is likely that you created a wrong project type or a file path error.

There are many features in liteide waiting for you to explore, but so far these are enough for us to use the go language.

Variables and simple data types

The go language contains all the simple data types you would expect from Uint8 to float64.

  • Uint8 unsigned 8 -bit integer number (0 to 255)
  • UInt16 unsigned number of integers (0 to 65535)
  • UInt32 unsigned number of integers (0 to 4294967295)
  • UInt64 unsigned full- scale integer ( 0 to 18446744073709551615)

  • Int8 8-bit integer number ( -128 to 127)
  • Int16 number of integers ( -32768 to 32767)
  • Int32 number of integers ( -2147483648 to 2147483647)
  • Int64 number of decimal integers ( -9223372036854775808 to 9223372036854775807)

  • float32 IEEE-754 Floating - point number
  • Float64 IEEE-754 Floating - point number

  • Complex64 Complex 32-bit real number + 32-bit imaginary number
  • complex128 Complex 64-bit real number + 64-bit imaginary number

  • a nickname for byte uint8
  • Rune Int32 's nickname

The biggest surprise is that the go language supports complex types of data:

var z complex64
z = 1.0 + 2.0i
Fmt. Println (z)

If you want to know what rune is, the problem should be solved when you know that Rune is used to store a Unicode character. In other words, Rune is equivalent to the Yu Gifu (char) type in the Go language.

Of course you can also use UINT, int Volume Two uintptr these types of integers that depend on the system type (32-bit or 64-bit).

Another new place, when you define a variable, you define the type of the variable behind it, not in front.

When you initialize a variable in the definition , you do not need to specify the data type for the variable. If it is not initialized at the time of definition , the variable will be given a value of 0:

var i=0
var x, y float32=1.0,2.0

As with numeric types,Boolean types have similar characteristics.

The compiler will do the work accordingly.

A simple example of defining and initializing variables using the Go language:

x,y:=1,2

You can also define and use constants.

Data

Commonly used data structures are strings (strings), arrays (arrays) and structs (structs), and another popular member map.

The string is Unicode encoded and its value cannot be modified, while others are similar to what you think.

S= "Hello"

You can use the Len function to get the length of a string , and you can access the characters in the string using the index operator [0]. The string types in the go language are fairly primitive, but using the STIRNG package enables all features similar to strings in other languages.

The array (arrays) is declared in brackets ([]), and the index starts at zero. For example:

var buff [32]byte
Fmt. Println (buff[10])

Multidimensional arrays are implemented by arrays of arrays,

var buff [32][32]byte
Fmt. Println (Buff[10][0])

The array is not dynamic and cannot be dynamically allocated size. However, you can use slices (slice) to achieve the same effect. Slices contain a portion of an array, which can be dynamically resized.

The structure (structs) is similar to other languages, as follows:

Func Main () {

Type point struct {
x, y int
}
var p = point{10, 10}
Fmt. Println (p.x)
}

The example above declares a new struct type, including two members X and Y. An instance of the struct type was created and initialized in the main function (instance). The go language typically does not use the term "instance (instance)" and prefers to use the term "value", so you are creating a value for that type (value).

struct definitions can be nested as members of structs. The initializer (initializer) {10,10} is a struct literal (literal can be understood as an immediate number, see Wiki). Member names such as {X:10} can also be used in struct literal.

This is the first time we've introduced the go type, and there's more to this topic.

The last data type is map, which is equivalent to a hash map in other languages, an associative array (associative array), or a dictionary (dictionary).

The type of the given key and the type of the value can create a map. If you have never used an associative array, think of it as an array whose values are not accessed through an index, but rather through a universal type of key. For example. :

var m = make (Map[string]int)
M["Mike"] = 10
M["Lucy"] = 30
Fmt. Println (m["Lucy"])

The display result is 30.

The Make function is one of the two functions that can create value (value) based on type (type), which is understood as an instance, and we need to learn more about the type of content to learn more about it.


Loading ...

The role of the go language differs greatly from the well-known object-oriented design language (Java, C + +), which has no hierarchy, no concept of classes, and no inheritance. Types can be inferred, such as: Go uses duck type.

You can define a type variable with an immediate number (literal ) or a specified type to achieve the purpose of type reuse.

A custom type is a combination of small data types, such as arrays, structs, pointers, well-acquainted, interfaces, slices, maps, and channel.

Methods for defining types:

Type name data type

Cases:

Type Myint int

Defines myint as an integral type. If you want to create an extension type, it is also common to redefine the data types of the previously declared types, and implement the functions and methods we'll talk about later.

More generally, you can use some data types to make up your custom types:

Type point struct {
x, y int
}

This is a new type structure.

You can also declare an array type:

Type MyArray [20]int

You can use a custom type when defining a type:

Type point struct {
x, y int
}
Type arraypoints [10]point

This creates an array of type point.

You can explore other types of definitions on your own. The next thing we need to do is understand what the go can do with these types of jobs?

Types are mainly used in the following two areas:

    • Type detection

And

    • Create a value

Type detection is common-you can only assign values of the same type to variables you define. A static type is checked by the compiler at compile time.

Cases:

var C Myint
c = "string"

The above code compilation will not pass. But the following code:

var C Myint
c = 1

will be compiled. Because both "C" and "1" are integral types of data.

The second thing you do: When you declare a variable with a type Constructs a variable of the corresponding type. such as:

var i int

or

Var p point

But for slice, map, and channel, they must use the Make function to create a value of the corresponding type.

var m = make (map[string]int)  

The Make function is one of two allocation functions supported by the go language, and the other is the new function. The Make function creates a value of the specified type and returns the worthy pointer to the variable. In most places, the pointer in go is similar to the pointer used in C.

You can use * to refer to the value of a pointer, or you can use & to get a worthy address. However, go and C pointers also differ, the difference being that the go language does not have pointer calculations. In the go language, the meaning of pointers exists is to allow you to pass arguments between functions in a reference way.

If you have a type T, then *t is a pointer to type T.

Give an example of the new function:

var add= new (int)

Here, the new function creates an integer variable and puts it back in the Add. The type of the variable add is *int.

If you write the following statement

FMT. Print (ADD)

Then you'll get this integer-worthy address. So, in order to print the value of this integer variable, we need to write the print statement like this:

FMT. Print (*add)

As mentioned earlier, you can use the value of a type directly without naming the type:

var p struct {
        x, y int
&nb Sp  

If you don't need to reuse this type, it's also possible.


Function

Go is not a class-based, hierarchical language and does not work with objects in the usual way. If you're just going to implement a function, you don't have to think about the object's content. A function is a value (values), which is a "one-class object."

As below, declare a function

var MyFunc = func (A, b int) int {
Return a + b
}
You can specify a parameter type and a return value type, and if you specify a return value type, you must have a return statement in the function.

The function values (value) are assigned to the variable myfunc. You can also define a function in the usual way, which is the variable myfunc is the name of the function.

Func MyFunc (A, b int) int {
Return a + b
}
Either way, the function can be called in the following way:

Fmt. Println (MyFunc (1, 2))

You can return multiple values in a return statement, and you can specify the name of the return value in the function header.

For example:

Func MyFunc (A, b int) (sum int) {
sum = a + b
Return
}
Sum is the return value of the function.

It's also easy to return multiple values:

Func MyFunc (A, b int) (int, int) {
Return a + B, a A
}
All two return values of the function must be received:

X, Y: = MyFunc2 (1, 4)
Fmt. Println (x, y)
In other languages, you can choose to receive only one return value, but not in the go language.


value--pointer

All the parameters are passed in as a value, so any changes to the parameters do not affect the arguments. For example:

Func MyFunc (A, b int) int {
    a = 1
    return a + b
}
The assignment statement for parameter A in the function has no effect on the argument. That means

x, Y: = 2, 3
var sum = myFunc (x, y)
Fmt. The Println (sum, x)
Displays the results as 4 and 2. The value of x does not change.

If you want to change the value of an argument, you need to pass in the pointer (that is, pass the address or pass the reference) as the argument. For example, the change function is defined as follows:

Func myFunc (a *int, b int) int {
    *a = 1
    return *a + b
}
parameter A with pointer In the form of an assignment to a, change the variable a points to. When calling a function, we need to pass in the address of the variable as a parameter:

var sum = MyFunc (&x, y)
Fmt. Println (sum, x)
now displays the result that the value of 4 and 1,x has changed. The use of the

* and & operators is very familiar to C programmers, which reflects the more elementary side of the go language. It is argued that all parameters in modern languages should be passed in by reference.

If the parameter in the function definition is a *int type, and the function is called without using the & operand, then an error is encountered during the compile-time type check, and the C language does not have this function.

In short, the pointer type of the go language can be passed as an argument to a function, but it is not possible to play some "smart" tricks on the data.

      

Scopes and closures

You can define functions in a function in a nested manner. A variable defined in a block of code will only take effect in that block code region and the area within that code region. This means that you can define global variables outside of the function, and all functions will be able to use this variable.

Cases:

var a1 int = 1
Func Main () {
Fmt. PRINTLN (A1)
var a2 int = 2
var MyFunc = func () int {
Return A2
}
Fmt. Println (MyFunc ())
}

In this example, A1 is a global variable that can be accessed by all functions. A2 is defined within the main function, so it can be accessed by the main function and the MyFunc function in main.

Go also supports closures. If you define another function in a function, the internal function will be able to access the variables of the external function, even if the external function has been terminated. The only way to persist an intrinsic function after an external function is stopped is to return it as a return value to the external function.

Cases:

Func MyFunc () func () int {
var a int = 1
return func () int {
Return a
}
}

Here, the intrinsic function is returned to the external function in the form of a func () int. The function and its contents are returned in the form of a type. The returned function returns the value of the variable defined by the external function, which is the function of the closure.

So

Myclosure: = MyFunc ()
Fmt. Println (Myclosure ())

The output result is 1.

Each closure has a copy of a variable bound to itself, and closures do not implement data sharing between different copies of the function.


Go Control

Now we've learned about data, types, and functions. Next we will discuss another important issue: the control statements provided by the go language.

In fact, the go language provides only a few control structures, which greatly simplifies the use of control statements.

The go language is a block-structured programming language that uses "{}" to block a set of code. If you have been in strange other programming languages often used in the ";" Where I go, I can tell you clearly that it still exists in go, but it will automatically add ";" To you during the compilation process. If you also add semicolons to the end of the code, the compiler will consider them to be unwanted characters and automatically reject the semicolons.

The For loop is the only loop in the go language. The For loop can be used to create conditional loops and enumerate loops.

The For loop has the following form:

For condition {
Operation
}

Note that you do not need to place the condition of the loop in a pair of curly braces "{}". The loop terminates when the condition is not met. The loop will check whether the condition is satisfied before each execution of the loop body, so the loop body can be executed 0 or more times, similar to the while loop.

Cases:

I:=0

For a<10 {
Fmt.print (a)
A=a+1
}

You can create a loop that does not terminate by using for true {"or" for {").

The enumeration loops are basically the same as other C-like languages:

For -expression 1 ; conditions ; Expression 3 {
Operation
}

Expression 1 executes once before the loop starts, and expression 3 executes once each time the loop body executes, and the condition statement is checked before each loop body execution, and if true resumes the loop.

Cases:

For i:=0; i<10; i++ {
Fmt.print (a)
}

You can include any statement in the for expression, but only if you have to add a semicolon to distinguish which part of the expression your statement belongs to. There is one exception, however, where you create a conditional expression without a conditional statement.

You can also repeatedly declare values in an array, slice, string, map, or channel in the for expression, using a For loop similar to that in other languages.

For example:

var array= [] int {1,2,3,4}
For i,v:= range Array {
Fmt.print (I,V)
}

The number of loops for the for expression depends on the size of the index and the array, like here I and V.


In the go language, there are two other kinds of control statements. The IF statement is basically the same as the IF statement in other languages, except for conditional statements surrounded by curly braces.

Cases:

If a<0 {
Fmt.print ("negative")
} else {
Fmt.print ("Positive")
}

The else condition is not required, but a pair of curly braces must be complete:

If a<0 {
Fmt.print ("negative")
}

You can also create a qualifying expression by using the else if:

If a<0 {
Fmt.print ("negative")
} else if a==0 {
Fmt.print ("Zero")
} else {
Fmt.print ("Positive")
}

You can also execute an initialization statement before the if principal content executes:

If A:=myfunc () a<0 {
Fmt.print ("negative")
}

All variables created in a conditional statement apply only in a conditional expression.

Another conditional expression is switch, which exists to deal with situations where there are more options in one condition. Such as:

Switch a {
Case 0, 1:
Fmt.print ("A is 0 or 1)
Case 2.3:
Fmt.print ("A is 2 or 3)
Default
Fmt.print ("A is some other value")
}

You can also write conditional statements in the following way:

Case A<0:

In the Go language, you do not need to break out of the criteria selection. If you want to go from one case to another, then you can use the Fallthrough statement (note:Fallthrough means to continue executing the following case instead of exiting Switch). The case statements are executed sequentially, and once the corresponding cases are executed, the program will automatically call break out of the selection after executing the statements in it, so the default option is often placed at the end.

In addition to matching values and conditions, you can match types such as:

Switch a.type{
Case INT:
Fmt.print ("A is an int")
Case Float64:
Fmt.print ("A is a float")
Default
Fmt.print ("Some other type")
}

Finally, you can use break to terminate the loop or continue to terminate the current loop and go directly to the next loop, which can also be used in a switch statement.

Although there are goto statements in the go language, this is not a good story.

Next section Trailer

In the next section we will learn how types in the Go language Create objects and invoke methods, interfaces.

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.