gogogo+ Basic notes on GO programming without a sniff

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

The go language is very convenient for web programming and is excellent for both development efficiency and program run efficiency. Compared to Java, its biggest advantage is easy to use, and compared to PHP, its biggest advantage is good performance.

(Go do the web) recommended gorilla Library, the inside of the route, CSRF pack up is very convenient.

If you want to use the Go language to do web backend development, I recommend you use Beego. If you have high performance requirements (don't want to reduce the performance by using the framework), I recommend you use gin.

The go language requires that a variable of public must start with a capital letter, and the private variable starts with a lowercase letter

No-smell video notes

Part of the code is not formatted!!

First lecture: Go common commands

Go get remote package (requires git installed in advance)
Go run
Go build Test Compilation (package main file)
Go FMT Format code
Go install compile package file and entire program
Go test Run the testing file (**_test.go is the test file, name your own files need to be noted)
Go Doc View document (local official website go-http=:8080 & background execution)

Comments:

 ///* */

Go structure

Second Lecture: Go program structure

    1. Package main contains the main function
      A program has only one main package and one main function
    2. Package to be placed on the first non-commented line
    3. Package Post plus Import,import introduction of non-main packages
    4. General recommended package name and directory name consistent pacage name do not use hump notation, use underline

VAR global variable
Type basic type such as: Type Newtype struct/interface{(content)}

Packagename.funcname the invocation of a method in a package

Change package Name:
Import abc "FMT"/import. "FMT"
Call the time
Abc. Println/println

It is not recommended. Kind of, easy to confuse

The third speaking go visibility rules (case!) )

The initial case determines whether constants, variables, types, interfaces, structures can be called externally
Function name first Letter lowercase =private
Function name First Capital letter =public

Q: Declaring multiple global variables, constants, structural fitness cannot be done together like import?
Answer: Yes, group. Only global variables, not in the body of the function
Type
Newtype int
Type1 string
)
The function body is AAA, BBB = 1, 2 is available
A, B, C, D: = 1, 2, 3, 4
(Note: = This declaration cannot be used outside of a function, and each syntax block outside of the function must start with a keyword.) )

Third speaking Go basic type

    • BOOL must be true, false. No numbers.
    • Int/uint/int8/unit8 (last, 64 bits, 8 bytes)
    • Byte (UNIT8)
    • Int32 (rune) hint processing Unicode characters
    • Plural: complex64/complex128
    • 32-, 64-bit integer that is sufficient to hold the pointer
    • Reference type: Slice,map,chan
    • Interface
    • Func, which can be assigned to a variable

Type 0 Value: Default value of some type, eg:int--0,bool--false,string--empty string: "", array does not give type--empty array [] array specify int (var a []int)--[0]

Types alias type (byte int8) strange things, give classes a name they like ┑ ( ̄д ̄) ┍

var b (int can be not) = 1 simultaneous assignment of the Declaration
If the type is not added, the system will judge by itself, if the type to be used later is different from the present declaration, it is best to mark the type after the declaration
D: = 456

_ Underline, blank identifier, can be ignored

Variable type conversions

    1. (No implicit conversions)
    2. can only be converted between two mutually compatible types
    3. Type conversion Format:
      var a float32 = 1.1
      b: = Int (a)

IV: Constants and Constants Enumeration

Constant enumeration

    1. Define a constant group: if you do not provide an initial value, use an upstream expression
    2. Using the same expression does not mean that you have the same value
    3. Iota is a constant counter, starting from 0 and automatically incrementing by 1 for each constant defined in the group.
    4. Enumeration effects can be achieved by initializing rules and iota
    5. Iota resets to 0 for each const keyword encountered
      eg
      const( a='A' b c=iota d)output: 65 65 2 3

Finally, the shift operation, the sense that the short time can not be used, the horse is free to see

V. Pointers, increment decrement, control statements

Pointer

Use. To operate
&
*
Default value nil, NOT NULL

Normal use:

a:=1var p *int = &afmt.Println(p)//output:addrfmt.Println(*p)//output:1即a

Increment Decrement statement

a++,a--cannot assign a value to a parameter, it must be put in a separate sentence
--,++ also cannot be placed on the left side of a variable

If

Without parentheses, spaces separated

if a := 1 ; a > 1//a为局部变量if a, b :=1, 2; a > 0//判断多个

For loop

Note: A function is not recommended in a conditional statement; The left brace needs to be on the same line as the statement

Three for loops

    1. First (write core code only)

      a:=1for{ a++ if a > 3 {   break }fmt.Println(a)}fmt.Println("over")
    2. The second Kind

      a:=1for a <= 3{ a++ fmt.Println(a)}fmt.Println("over")
    3. A more common form

      a:=1for i:= 0; i < 3; i++{ a++ fmt.Println(a)}fmt.Println("over")

Switch does not break, match auto stop, if match still want to continue, want to Fallthrough


Fallthrough


Support initialization expression, right side semicolon (Switch A: = 1; {... This initialization is a local variable, and a switch cannot be used.

goto; break; continue.

Use with tag name
Break and continue can jump out of multi-layer loops (in combination with label, which level the label can jump to)


Break+label
Continue+label

The question is: what happens to continue to goto--infinite loops

Array

The array length is also considered a type
var a [2]int
var b [1]int
A =b not legal
A: = [...] Int{0:1,1:2,2:3}
Initialization can be given no number of elements, and indexes can specify only one value
var p [100]int = &a Pointer to array
A: = [...]
Int{&x,&y} An array holds pointers to two variables

Two modes of delivery:

    1. An array is a value type that is passed as a copy rather than as a pass-through address.
    2. If you want to pass the address, called the reference type, slice, can be implemented, similar to dynamic array, reference passing

Between arrays can be = = or! = (see above, different types of arrays can not do any direct comparison)

Pointer to array (the return value of new is a pointer, generally not new)
P: = new ([10]int)//output is also a pointer to an array


Two different ways

Multivariate arrays (outermost best defines the length of each array, do not use ... )

a := [2][3]int {  {1,1,1}  {2,2,2}}

Seventh Lecture Slice

    1. itself is not an array, pointing to the underlying array, can be associated with the underlying local or all
    2. Type
    3. Len () Gets the number of elements, the cap () gets the capacity, and the capacity is the number of contiguous blocks of memory, such as the array 1-10,slice3-5,cap3-10
    4. Multiple slice point to the same underlying array data, change one, change all
    5. declaring Var si []int/a:= []int and arrays is the difference between [] there is no number and no ...
      You can also use make () to declare
      S1: = Make ([]int,3,10) int, 3 elements, CAP10, if greater than 10, will become 20, not set capacity will be considered capacity = number of elements

Slice today encountered a small pit, when initializing the slice, want to give slice the length of a variable, only with Exampleslice:=make ([]int,variablea+1) This make initialization mode, examslice:=[] INT{VARIABLEA+1:0} This is not possible, it must be a const,var.

The difference between new and make:

func new(Type) *Type # 返回一个指针 func make(Type,size,IntegerType) Type # Type必须是引用类型(Slice,Map,Channal等)返回一个对象,而非指针

Reslice

Slice on the slice.
Out of bounds will be an error

Append

Append an element to the slice tail, or append another slice (much like stitching two arrays)
If the cap is exceeded, the original data is copied


Example

After the first append, the address of the output is not changed, because no more than the CAP, the second append after the address changes, the words will be copied to the memory of the reallocation

Copy


The output is 7 8 9 4 5 6, which in turn s2--s1 the result is 1 2 3 (whichever is shorter)

Eighth, map

Key-value faster than linear lookups, but much slower than indexes (arrays and slice)
Key must be comparable, slice,func can not
Disclaimer: var m map[int]string/m: = Make (map[int]string)

Assignment: m[1] = "OK"//key=1,value= "OK"
Delete: Delete (m,1)

var m map[int]map[int]string
M=make (map[int]map[int]string)//Only initial layer map
M[1] = make (map[int]string)
M[1][1] = "OK"
a:= M[1][1]
Output A is OK


Map nesting map When you are aware of each initialization, check whether the initialization method: Double return value, if not initialized, OK returns false

Iteration
For range (like for each)

General form: for i,v: = Range Slice {output i,v}, equivalent to an enumeration, V is an element value, but a copy, cannot modify the element value of the slice itself, but can modify slice[i]

For k,v: = range map{Output key-value pairs, but all operations on copy values, Map[k] can change the value in map}
MAP[K]

There's a very good example of the legend.

func main(){  sm := make([]map[int]string,5)//以map为元素的slice  for _,v := range sm {    v= make(map[int]string,1)    v[1] = "OK"    fmt.Println(v)//打印map[1:ok]  }  fmt.Println(sm)//打印空map,因为v改变不影响slice}

Output map[1:ok]map[1:ok]map[1:ok]map[1:ok]map[1:ok][map[] map[] map[] map[] map[]


SM[I],SM[I][1] can change the map value in slice

Really good example, a bit around
Application: You can sort the map by sorting the Mapkey
Convert key to int in a slice and sort.ints (s)

Assignment: Swap the map in V,k,
Solution: for K,v: = Range m1{
M2[V] = k}

Nineth Lecture: Func

    1. Nested, overloaded, default parameters are not supported
    2. Support does not need to declare the prototype can be used, variable length arguments (parameter place can be written ... ), multiple return values, named return value parameters, anonymous functions, closures
    3. Can be used as a type
    4. The keyword Func {to be on the same line

Declaration: If the parameter type is the same (the parameter and the return value are Type1=type2, you can write only the last one; the return value can not be named) func funcname (para1 type1, Para2 type2) (Returnvalue1 type1, Returnvalue2 type2) {
}


Funca changes do not affect the slice value, (int parameter pass, do not change the original value) output A, B or
Funca changes affect slice value, direct incoming slice, reference delivery, copy address
If you want to change the int value, you need to pass the pointer
Everything is type, function can also be type, a calls a, output will print Func A

anonymous functions

A: = Func () {
Fmt. Println ("Func A")
}
A ()

A is the variable of the type of the subsequent function, which is called the anonymous function

Closed Package

Requires programming basics and understanding of closures
Closed Package
Another closure example, read the one can understand

Returns an anonymous function


Output is 11, 12, and the same address (confirmed to be a closed packet)

Defer

    1. Similar destructors
    2. After the function body executes, it executes in reverse order of the call order.
    3. A function with a critical error will also execute
    4. Support for anonymous functions
    5. Application: Resource cleanup, unlock, record time, file close, return to modify calculation results
    6. If a variable in the function body is a parameter of an anonymous function when defer, then a copy is obtained when the defer is defined, otherwise it is a reference, the reference address
      Like what:
      for i:=0; i<3;i++{defer func(){打印i}}//输出210,i作为参数传递进去for i:=0; i<3;i++{defer func(){ 打印i}() //这个括号是类似defer a()}//输出333,闭包,i一直作为引用

Go exception handling mechanism, similar to Finaly--panic/recover mode to deal with, panic can be raised anywhere, recovery only in the defer only effective

Panic (), execution of the program will terminate


Defer to be placed in front of panic, the lower right corner of the figure is the output

Homework:


Analysis program Run results

First output is fs[i], and then with the next for loop output FS This slice value, I for the outer for Loop I reference address, executes the first for loop, i=4, so the second for loop output is =4
Then executes the second defer in the first for loop for the first time, the first defer is a value copy, so the value is modified ... Actually not very understand ┑ ( ̄д ̄) ┍

Tenth talk structure struct

    1. Go does not have class,struct similar class
    2. comparison, names and other places are the same can be compared, the name is not the same can not, the name is different type
    3. Support Anonymous, anonymous structure can be used for map, can compare
    4. Allow reading and writing of struct members through pointers
    5. Initialization
      meStruct := new(SmallSoho) //初始化一个空的结构体,返回指针meStruct := &SmallSoho{} //同上meStruct := SmallSoho{} //返回一个空结构体meStruct := &SmallSoho{Name:"SmallSoho"} //也可以键值对这样来初始化

      struct INIT

      If you want the changes in Func to take effect on the original data, you need to take the address, otherwise you get a copy of the value, changing it does not change the original value
      Recommendation: For struct initialization when the habit plus take the address character Eg:&person, easy to follow-up operation
    6. Anonymous structure
      a := &struct {Name stringAge int}{Name: "Joe",Age : 19,}fmt.Println(a)
      Nested struct (like inheritance), anonymous structure

      Nested struct, anonymous, with. Call, name age these can also not write, if not written, need to note the order

Human sex nested inside
Output results

If you want to set up sex,a := teacher{Name: "joe",Age:19,human:human{Sex:0}}
If you want to modify

a.Name = "Joe2"a.Sex = 100//注意,这里直接加sex就可以了

Xi. method

Func (a A) print () {}
Called when the A.print
A of type A is the recipient


Output TZ
Two methods of invocation: Method-value; method-expression

Sibling names do not conflict

Call the method found first

Method access Permissions Issue:
In the same package: method can access the private and public fields of a struct

Homework:


Paste_image.png
Work on the code in the course of change
Answer on GitHub with code files

12 Speaking interface

    1. Only declarations, no implementations, no data
    2. Implementation interface: Structural typing, as long as the implementation of a certain type of all methods of the interface signature, even if the implementation of the interface
    3. A function similar to inheritance is implemented through an interface.
    4. All types in go implement an empty interface, and an empty interface can be used as a container for any type of data
    5. interface conversion, large interface to small interface can be nested into the small interface will not go to the big Street
    6. object is copied when assigned to an interface, so the interface content cannot be changed by modifying the object
    7. Interface stores the type and object are nil interface is nil, if the interface is stored in the pointer to nil, nor
    8. Type assertion OK Pattern/type switch type judgment, interface conversion

Interface
If a specific type implements an interface, the value of this specific type can be used either as a value of that interface type or as a value of that specific type

Note: Pointer method set, if the pointer is passed in, you can call Reveicer is a pointer and not a pointer to the method, if passed in a non-pointer method set (copy) cannot call pointer method solution, so the interface receiver does not do automatic conversion, because it is a copy of the


Connecter Nested interfaces

13 speaking reflect

(Start a little to understand, at present, look at the code phase, estimated to understand a few basic methods will be skipped, see later)

    1. TypeOf ValueOf get information from the interface, combined with an empty interface interface{}

Example. png

The field in the reflect package reflects the structure information

Reflection
The go language implements reflection and reflection is the state of the dynamic runtime. The package we usually use is a reflect bag.

The use of reflect is generally divided into three steps, the following brief explanation: to go to reflect is a type of value (these values are implemented in the empty interface), first need to convert it to reflect object (reflect. Type or reflect.value, calling different functions depending on the situation).

The two ways to get these are:
T: = reflect. TypeOf (i)//get the type of metadata, through t we can get all the elements inside the type definition
V: = reflect. ValueOf (i)//get the actual value, through v we get the value stored in it, we can change the value

After converting to a reflect object, we can do something, that is, convert the reflect object to the corresponding value, for example
Tag: = T.elem (). Field (0). Tag//Get the label defined in the struct
Name: = V.elem (). Field (0). String ()//Gets the value stored in the first field


Use the reflect package function to find the specified field name and change its value

Dynamic Call method


Output:hello Jeo, my name is OK

14 Speaking concurrent concurrency

Goroutine Super Thread pool
4-5k per instance, lightweight

Concurrency is not parallel: concurrency is performed "simultaneously" by switching time, and parallelism is multi-core multithreading

Goroutine communicate to share memory instead of shared memory

A basic concurrency

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.