Go from getting started to mastering (i) First __go

Source: Internet
Author: User
One, the first go program
Package main

Import (
       "FMT"
)

func main () {
       fmt. Println ("Hello World")
}

For the explanation of the code

If it is to compile the code into an executable program, then package must be the main
If it is to compile the code into a library, then package is not limited
All code in go should belong to a package

FMT is a system library for Go

FMT.PRINTLN () You can print the output

If you want to run the program: Go Run program name

There is only one main function in an executable program

About annotations

Single-line Comment://
Multi-line Comment: /*/II, go language first knowledge

About defining a variable

var variable name variable type
Variable name = value

Note here: The variables defined in the Go language must be used, or they will be an error
Defining variables and assigning values can be done in one step: variable name: = value

Define a function

If we want to define a function, let's look at the following example of summation:

Func Add (a int,b int) int {
    var sum int
    sum = a + b return
    sum
}

Here we need to know that the following format is strictly required not including the first line of curly braces cannot be placed on the next line
Func function name (parameter 1 parameter 1 type, parameter 2 parameter 2 type) return value type {

third, Golang language features

Garbage collection

Automatic memory recovery without the need for developers to manage memory
Developer Focus on business implementation
Only need new to allocate memory, no need to release

Natural high concurrency from language Zeng Meta support concurrency, very simple goroute, lightweight threading, creating thousands of goroute possible implementations based on CSP model

A simple demo of high Concurrency:

Package main

Import (
    "FMT"
    "Time"
)


func test_print (a int) {
    fmt. Println (a)
}


func main () {for
    i:= 0;i < i + + {go
        test_print (i)
    } time
    . Sleep (time. Second)
}

When you implement high concurrency, you only need to precede the called function with go, which means that the concurrency is turned on

If you do not add time to the outside of the For loop. Sleep (time. Second), you will find that it will print less, because when the main program is finished, it will not wait for the thread, so the program terminates directly

Channel Pipeline

Pipe similar to Linux
Communication between multiple Goroute through the channel
Supports any type

Package main

Import (
    "FMT"
)

func test_pipe () {
    Pipe: = Make (chan int,3)
    pipe <-1
    pipe <-2
    Pipe <-3

    FMT. PRINTLN (len (pipe))
}

func main () {
    test_pipe ()
}

Explanation of the above code:
Pipe: = Make (chan int,3) Here is the definition of a pipe pipe,go is a strongly typed language, so declare a pipe variable pipe need to pass three arguments, Chan says is pipe, int represents pipe type, and 3 indicates pipeline capacity
The length of the pipe can be viewed through Len (pipe)

If you want to get data from the pipeline
T1: =<-pipe This is equivalent to
var T1 int
T1 = <-Pipe
Fmt. PRINTLN (T1)
The principle that the pipe follows is FIFO first, so the first fetch value is 1

Summary: If you want to put a value on a pipe: defined pipe pipe <-what to deposit
If you want to get a value from a pipeline: variable name =<-defined pipe pipe

Here we emphasize the concept of the package package in go, a variable in a package, it is accessible in this package, but there is also permission to restrict access to the package, and if a variable is capitalized in one package, it can be accessed in other packages and not in other packets in lowercase. Similar to public and private in other languages

Multiple return values

A function can return multiple values

Package main

Import "FMT"

func calc (a int,b int) (int,int) {
    sum: = a + b
    avg: = SUM/2 return
    sum,av G
}

func main () {
    Sum,avg: = Calc (100,200)
    FMT. Println (SUM,AVG)
}

When you need to pass in more than one parameter in parentheses, a single case is generally not enclosed in parentheses, direct int, and here is the return of two (int,int) means to return two integer type values

If you have more than one return value, but I just want to return a value that is implemented by underlining, the preceding code should read:

Func Main () {
    sum,_: = Calc (100,200)
    FMT. Println (sum)
}
Iv. The concept of packagesLike Python, the code for the same function is placed in a directory, which is called a package that can be referenced by other packages. The main package is used to generate executable files, and each program has only one main purpose of the package is to improve the class reusability of the code

About the main function in the main package, the GO program after compiling, run the program, will be compiled binaries loaded into memory, will first call the main function, so the main function is the entry function of the program, that is, must have package main

With regard to packages, we can encapsulate some commonly used functions into packages, at the beginning of each go file in the package, instead of package main, the custom name of package is named according to the function of the package.

Go source is organized by package and package to the first line that is not annotated
A program has only one main package, one package can only have one main function, cannot repeat the definition
The main function is the execution portal of the program
No referenced variables, error when compiling

Directory specification for Go

Here's a simple example: if we're building a go_project directory, usually in this directory we'll create the following directory
SRC holds different project codes
Bin holds compiled executable program
Vender a third-party library that holds references
PGK Store Static Library

The Gopath in our GO environment variable are typically set to:
(I'm the path here is/users/zhaofan/go_project)
Export Gopath=/users/zhaofan/go_project

Go's compilation

If we write down the Go code file, we can pass the test run:
Go run fast execute go file
Go build compile program, generate binary file
Go install install executable file into bin directory

Basic commands:
Go test performs unit tests or stress tests
Go env shows GO-related environment variables
Go FMT Format Source code

We understand the use of this compilation command through the following examples:

Example One

I wrote a hello program under the/users/zhaofan/go_project/src/go_dev/day01/hello directory.
Now compile this Hello program

The compile command we execute in the Go_project directory, if you do not specify that the compiled file will generate the compiled file directly in the current directory, the Go_project directory
What you need to explain here is the path to build Go_dev/day01/hello
We can see from the directory structure, Go_dev of the top level of the directory src is not written, this is because go compile, will automatically to Gopath under the SRC directory to find, so here is not need to write, At the end of the compiled path we only write to the Hello directory instead of the Hello.go file

Example Two

We set up a Goroute directory under the/users/zhaofan/go_project/src/go_dev/day01/directory
and create two go files, main.go and goroute.go files in the Goroute directory

The code for the Main.go file is:

Package main
import (
       ' time '
)

func main () {for
        I: = 0; i < MB i++ {go
            test_goroute (i)
        } Time
        . Sleep (time. Second)
}

The code for the Goroute.go file is:

Package main

Import "FMT"

func test_goroute (a int) {
    fmt. Println (a)
}

This allows us to compile with only the Go_project directory to execute:
Go Build Go_dev/day01/goroute
This will then generate an executable file in the Go_project directory Goroute

Example 3
or set up a goroute_test directory under the/users/zhaofan/go_project/src/go_dev/day01/.
Create a calc directory and a main directory under the Goroute_test directory
At the same time, create a sum.go file under Calc, and create a main.go file in the main directory.

Su

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.