Golang Introductory Tutorial (i): Basic Concepts _golang

Source: Internet
Author: User
Tags closure rand

Install Golang

The http://golang.org/dl/can be downloaded to Golang. Installation Documentation: Http://golang.org/doc/install.

Hello Go

We first create a file Hello.go:

Copy Code code as follows:

Package Main

Import "FMT"

Func Main () {
Fmt. Printf ("Hello golang\n");
}

Execute this program:

Copy Code code as follows:

Go Run hello.go

Package

The Golang program consists of a package (packages), which runs from the main package:

Copy Code code as follows:

Package Main

This statement indicates that this file belongs to the main package (multiple source files can belong to the same package). The import statement is followed by the path where the package is located (called the package path or the import path), and a package is placed in a directory, usually with the same directory name and package name:

Copy Code code as follows:

Import (
"FMT"
"Math/rand"
)

Here the "FMT" and "Math/rand" are package paths (import Paths). The import statement above can also be written like this:

Copy Code code as follows:

Import "FMT"
Import "Math/rand"

Once we have imported the package, we can refer to the exported name by "package name. Name", for example:

Copy Code code as follows:

Import "FMT"

The FMT package exports Printf
Fmt. Printf ("Hello golang\n");

In Golang, a name, if the first letter is capitalized, indicates that the name is exported.

Function

Copy Code code as follows:

Package Main

Import "FMT"

Func Add (x int, y int) int {
return x + y
}

Func Main () {
Fmt. Println (Add (42, 13))
}

Note that the variable name is not the same as many languages before the type. Another x int, y int can also be written as x, y int:
Copy Code code as follows:

Func Add (x, y int) int {
return x + y
}

Functions can return multiple values:

Copy Code code as follows:

Package Main

Import "FMT"

Func swap (x, y String) (string, string) {
return y, X
}

Func Main () {
A, B: = Swap ("Hello", "World")
Fmt. Println (A, B)
}

The return value can be specified as a variable name and used like a variable:

Copy Code code as follows:

Package Main

Import "FMT"

Func split (sum int) (x, y int) {
x = sum * 4/9
y = sum-x
Return
}

Func Main () {
Fmt. Println (Split (17))
}

You can see that the split function directly uses the return statement without parameters.

Variable

The declaration of a variable uses the var statement:

Copy Code code as follows:

var i int
var c, Python, Java bool

A variable can be initialized when it is declared:

Copy Code code as follows:

var x, y int = 1, 2
var i, j = true, "Hello"

We see that you can specify or not specify the type of the variable when initializing.
According to Golang's syntax, any structure outside the function (construct) starts with a keyword, such as when the variable starts with the var keyword, and the function starts with the Func keyword. Within a function, variable assignment can be used: = operator:

Copy Code code as follows:

Package Main

Func Main () {
var x, y int = 1, 2
I, J: = True, "Hello"
}

: = The left of the operator is a variable, and the right is a value.

Data type

Basic data type:

1.bool
2.string
3.int int8 int16 int32 Int64
4.uint uint8 uint16 UInt32 UInt64
5.uintptr
6.byte (equivalent to uint8)
7.rune (equivalent to Int32, used to represent a Unicode code point)
8.float32 float64
9.complex64 complex128

A type conversion uses an expression T (v), meaning to convert V to type T:

Copy Code code as follows:

var i int = 42
var f float64 = float64 (i)

I: = 42
F: = Float64 (i)

Type conversions always need to be done explicitly.

Use const to declare constants:

Copy Code code as follows:

Const PI = 3.14

Const (
Big = 1 << 100
Small = Big >> 99
)

Control statements

For statement

Golang uses (and only uses) for To loop (no while statement):

Copy Code code as follows:

Package Main

Func Main () {
Sum: = 0

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

This type of writing is equivalent to the while statement in languages such as C + +
For sum < 1000 {
sum = Sum
}
}

Unlike languages such as C + +, you do not need () and {} are required to use a For statement (the following if, switch is the same as the syntax processing). If you need an infinite loop, then use:

Copy Code code as follows:

for {
}

If statement

The IF statement can take a statement before the execution condition is judged (this is often called an if with a phrase), and the life cycle of the variable in this statement ends after the IF statement ends. For example:

Copy Code code as follows:

Package Main

Import (
"FMT"
"Math/rand"
)

Func Main () {
If n: = Rand. INTN (6); N <= 2 {
Fmt. Println ("[0, 2]", N)
} else {
Fmt. Println ("[3, 5]", N)
}

You can't start with variable n here.
}

Switch

Copy Code code as follows:

Package Main

Import (
"FMT"
"Runtime"
)

Func Main () {
Fmt. Print ("Go runs on")
Switch like if can take a phrase sentence
Switch OS: = Runtime. GOOS; OS {
Case "Darwin":
Fmt. Println ("OS X.")
Case "Linux":
Fmt. Println ("Linux.")
Default
FreeBSD, OpenBSD,
Plan9, Windows ...
Fmt. Printf ("%s.", OS)
}
}

Unlike languages like C + +, Golang does not need to use break statements to jump out of a switch. In addition, the switch can have no conditions:

Copy Code code as follows:

Package Main

Import (
"FMT"
"Time"
)

Func Main () {
T: = time. Now ()
Switch {
Case T.hour () < 12:
Fmt. Println ("Good morning!")
Case T.hour () < 17:
Fmt. Println ("Good afternoon.")
Default
Fmt. Println ("Good evening.")
}
}

Defer

A defer statement can add a function call to a list (this function call is called a deferred function call) and call the function in the list at the end of the current function call. Example:

Copy Code code as follows:

Func CopyFile (DstName, SrcName string) (written int64, err error) {
SRC, err: = OS. Open (SrcName)
If Err!= nil {
Return
}
Defer src. Close ()

DST, err: = OS. Create (DstName)
If Err!= nil {
Return
}
Defer DST. Close ()

Return IO. Copy (DST, SRC)
}

Deferred function calls are performed in an advanced sequential order:

Copy Code code as follows:

Package Main

Import "FMT"

Func Main () {
For I: = 0; I < 5; i++ {
Output 43210
Defer FMT. Print (i)
}
}

Structure (structs)

A structure is a collection of domains:

Copy Code code as follows:

Package Main

Import "FMT"

Type Vertex struct {
X int
Y int
}

Func Main () {
V: = vertex{1, 2}
v.x = 4
Fmt. Println (v)
}

The pointer is present in the Golang, but the pointer does not support arithmetic operations:

Copy Code code as follows:

P: = vertex{1, 2}//{1, 2} for struct literal
Q: = &p//q type is *vertex
q.x = 2//Direct access domain X

As seen above, struct's literal is wrapped by {}, in struct literal we can use the syntax "Name:" To set a value for a particular field:

Copy Code code as follows:

Type Vertex struct {
X, Y int
}

R: = Vertex{x:3}//This time Y is 0

New function

We can assign a value initialized to 0 and type T by expression new (t), and return a pointer to this value, as follows:

Copy Code code as follows:

var p *t = new (T)
P: = new (T)

A more detailed example:

Copy Code code as follows:

Package Main

Import "FMT"

Type Vertex struct {
X, Y int
}

Func Main () {
V: = new (Vertex)
Fmt. Println (v)
v.x, v.y = 11, 9
Fmt. Println (v)
}

Arrays and Slice

N T is a type (just like *t) in Golang, representing an array of length n whose element type is T. Example:

Copy Code code as follows:

Package Main

Import "FMT"

Func Main () {
var a [2]string
A[0] = "Hello"
A[1] = "World"
Fmt. Println (A[0], a[1])
Fmt. Println (a)
}

Note that the length of the array cannot be changed.

A slice is a data structure that points to a contiguous part of an array. Slice is very much like an array. []t is the slice type, where the element type is T:

Copy Code code as follows:

Package Main

Import "FMT"

Func Main () {
Build a slice
P: = []int{2, 3, 5, 7, 11, 13}
Fmt. Println ("p = =", p)

For I: = 0; i < Len (p); i++ {
Fmt. Printf ("p[%d] = =%d\n", I, P[i])
}
}

The expression S[lo:hi] is used to create a slice, and the newly created slice element is an element of the [lo, hi] position in S.

Create slice use the Make function (instead of the new function, because you need to set additional parameters to control the creation of slice):

Copy Code code as follows:

Len (a) is 5
A: = Make ([]int, 5)

Here the Make function creates an array whose elements are initialized to 0 and returns a slice point to the array. Make can take a third parameter to specify the capacity:

Copy Code code as follows:

Len (b) is 0
Cap (b) is 5
B: = make ([]int, 0, 5)

b = B[:cap (b)]//Len (b) =5, Cap (b) =5
b = b[1:]//len (b) =4, Cap (b) =4

A slice with no value is nil, with a length and a capacity of 0.

Copy Code code as follows:

Package Main

Import "FMT"

Func Main () {
var Z []int
Fmt. Println (z, Len (z), Cap (z))
If z = = Nil {
Fmt. Println ("nil!")
}
}

Range

Range is used in the for to iterate over a slice or a map:

Copy Code code as follows:

Package Main

Import "FMT"

var s = []int{1, 2, 3}

Func Main () {
For I, V: = range S {
Fmt. Println (i, v)
}

Only need value, use _ Ignore Index
For _, V: = range S {
Fmt. Println (v)
}

only need index
For I: = range S {
Fmt. Println (i)
}
}

Map

Map is used to map key to value (value). A map can be created by make (not new):

Copy Code code as follows:

Package Main

Import "FMT"

Type Vertex struct {
Lat, Long float64
}

var m map[string]vertex

Func Main () {
m = Make (Map[string]vertex)
m["Bell Labs"] = vertex{
40.68433,-74.39967,
}
Fmt. Println (m["Bell Labs"])
}

Map iteral Much like struct literal:

Copy Code code as follows:

var m = map[string]vertex{
Here Vertex can be omitted not to write
"Bell Labs": vertex{
40.68433,-74.39967,
},
"Google": vertex{
37.42202,-122.08408,
},
}

Use [] to access the values in the map, using Delete to delete the values in the map:

Copy Code code as follows:

M[key] = Elem
Elem = M[key]
Delete (m, key)

If you need to check whether a key in the map is in use:
Copy Code code as follows:

Elem, OK = M[key]

Elem represents the value of the key (when key does not exist, Elem is 0), OK indicates whether the key exists.

Closed Bag

A function in Golang is also a value (like an int value), and a function can be a closure. A closure is a function that references an external variable. Look at an example:

Copy Code code as follows:

Package Main

Import "FMT"

Func adder () func (int) int {
Sum: = 0
Returns a closure that references the external variable sum
return func (x int) int {
sum = X
return sum
}
}

Func Main () {
A: = Adder ()
Fmt. Println (A (9527))
}

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.