Go Language Learning Note 1/2

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

Book: "Go Language Programming"

Chap 1 First knowledge of Go language

1.Go language Features: Automatic garbage collection, richer built-in types, function multiple return values, error handling, anonymous functions and closures, types and interfaces (not supported for inheritance and overloading, support for combinations only), concurrent derogatory, reflection, and language interactivity.
The main function of the 2.Go language cannot have parameters and cannot have a return value. Go language function definition:
Func function name (argument list) (return value list) {//function body}
3. Compile: Go build hello.go; compile run, do not produce intermediate compile file and execute file: Go run hello.go

Chap 2 Sequential programming
The 1.Go language does not require semicolons.
2. Variable declaration using the keyword VAR, in the format: var variable name variable type
3. Three ways to initialize variables:
var v1 int = 10
var v2 = 20//Auto Derivation
V3: = 30//Auto-derivation, complete declaration and initialization, generates variable v3, so V3 cannot be a declared variable
Although it can be deduced automatically, the go language is a strongly typed language.
4. Supports multiple assignments, for example: i,j=j,i//interchange I, J variable value
5. The variable in the function parameter is an anonymous variable.
6. Defining constants: Using the CONST keyword: const Pi float64 = 3.1415926
7. Predefined constants: True, False, and iota (constants that can be modified by the compiler, reset to 0 when each const keyword appears, and when the next const appears, does not appear once iota, and its value is 1).
8. Enumeration type:
Const
Sunday=iota
monday//will automatically deduce that Monday equals 1.
Tuesday
numberofdays//only uppercase letters of the external package are released, the lowercase letters start not released
)
9. Type:
1) Boolean type bool:v2: = (1==2) Boolean type does not support type conversion
2) Shaping: Int32, Int64, etc. are fixed-size, int, UINT is platform-related, we recommend using platform-related types. Different types, such as int and Int32, are not comparable and compile errors, but can be compared to literal constants such as i==1.
3) Floating point type: cannot be compared directly = =, you can import math and set the range for equal comparison according to the size of the difference.
4) Complex Type Complex:var a complex
5) string String:var str string
Accessed by a similar array subscript, but cannot be modified. The default is UTF-8 characters, and Chinese includes three bytes. Traversing Chinese is a Unicode character traversal of a string using the range function.
6) Character type: Byte represents a single utf-8 byte (three bytes for a Chinese character), and Rune represents a single Unicode character (one character per kanji).
7) array type: array name [number] Type
The array type is a value type, so the internal copy process occurs if the function parameter is an array.
8) Slice slice: understood as an array that can be dynamically expanded, the copy process does not occur when a function parameter is passed.
A. Creating slices based on arrays: myslice=myarray[n:m]
B. Using the Make function: Myslice:=make ([]int,5)
9) Map type: var myMap map[key] Value, can be created using the Make function.
Check for presence: Value,ok: = mymap["Key" to determine OK
10. Process Control
1) Conditional statement:
A.If: The condition is without parentheses, and the curly braces follow the IF, else line.
Func calc (x int,y int) int {
If X>y {
return x
} else {
Return y
}
}
The variables behind the B.switch:switch can not be written, and the case can be expressions (i>5 && i<10), not to be thanked Break,fallthrough follow-up.
Func calc (i int) int {
Switch I {
Case 0:
Fallthrough
Case 1:
Fmt. Println ("1")
Case 2:
Fmt. Println ("2")
Case 3:
Fmt. Println ("3")
Default
Fmt. Println ("Default")
}
Return 7
}
2) Loop statement: supports only for statements. For no need (), even I can not use I (direct loop, use break, similar to while)
Func calc (x int) int {
Sum: = 0
For i:=0;i<x;i++ {
Sum+=i
}
return sum
}
3) Jump goto:
Func calc () int {
Sum: = 0
Here:
Fmt. PRINTLN (SUM)
sum++
If sum<100 {
Goto HERE
}
Return 7
}
11. Functions:
1) can accept the indeterminate parameter func myfunc (args ... int) and then use range traversal (syntactic sugar structure, which is more convenient to call, without having to pass in parameters using the new int[]{1,2,3} style)
2) variable parameter support slicing operation
3) support multiple return values, use _ Skip the return value you do not want to use
Package Main
Import (
"Errors"
"FMT"
)
Func Add (A, B int) (ret int, err error) {
If a<0 | | b<0 {
Err = errors. New ("should be non-negative numbers!")
Return
}
Return A+b,nil
}
Func Main () {
Fmt. Println (ADD (1,3))
}
12. Anonymous functions and closures:
1) Anonymous functions can be assigned directly to a variable
F:=func (x, y int) int {
Return X+y
}
2) Closures: Understood as anonymous function + system environment (variables in code, etc. are no longer defined in code)
F:=func () (func ()) {
var i int = 10
return func () {
Fmt. Printf ("i,j:%d,%d\n", I,j)
}
}()
F ()
j*=2
F ()
Note: The function func is defined, the return type is func (), and the last need to add () so that I cannot be accessed externally, then the defined J can be different after multiple invocations of F.
13.defer (deferred function) is defined and then invoked in an advanced, post-out method. After the panic () function call: The normal function execution process terminates immediately, but the statement in the function that was previously deferred with the DEFER keyword will execute normally, after which the function returns to the calling function and causes

Executes the panic process up and down until all the executing functions in the owning goroutine are terminated. The Recover () function is used to terminate the error handling process.

CHAP03 Object-Oriented programming
1. The definition type uses the type keyword, for example:
Type Integer int
Add a method to the integer as follows:
Func (a integer) less (b integer) bool{
Return a<b
}
If you want to modify the value of a type, you need to use pointers, such as Func (a *integer) ...
Most of the 2.Go languages are value references (including arrays), and the referenced modifications do not change the referenced values.
3. Define the type using the struct keyword, with the following example:
Package Main
Import "FMT"
Type Rect struct {
X, y float64
}
Defining methods
Func (R Rect) area () float64 {
Return r.x * R.Y
}


Func Main () {
R: = &rect{10,20} Initialize 1
Fmt. Print (R.area ())
Fmt. Print ("\ n")
S: = new (Rect) Initialize 2
Fmt. Print (S.area ())
Fmt. Print ("\ n")
T: = &rect{x:30,y:40} Initialize 3
Fmt. Print (T.area ())
}
4.Go provides inheritance attributes in a combined way, called anonymous combinations. The combined method can be called directly.
Package Main
Import "FMT"


Type Base struct{
Name string
}
Func (b *base) Sayhi () {
Fmt. Print ("Hi, base!\n")
}


Type Child struct{
Base
}


Type Child1 struct{
*base
}
Func (c *child1) SayHi1 () {
C.base.sayhi ()
}
Func (c *child1) SayHi2 () {
C.sayhi ()
}


Func Main () {
B: = &base{}
B.sayhi ()
c: = &child{*b}
C.sayhi ()
D: = &child1{b}
D.sayhi ()
D.base.sayhi ()
D.sayhi1 ()
D.sayhi2 ()
}
5. Visibility, uppercase means visible to the outside, lowercase is only visible within the package.
In 6.Go languages, as long as a class implements all of the interface's methods, it means that the class implements the interface. The interface is defined as follows:
Package Main
Import "FMT"


Type File struct{
Name string
}
Func (f *file) Read () {
Fmt. Print ("Read")
}


Type IFile Interface {
Read ()
}


Func Main () {
var ifc IFile = new (File)
Ifc. Read ()
}
7. Interface assignment is similar to type conversion, and can be converted from an interface to a small number of interfaces.
8. Interface query:
If File,ok:file1. (IStream); ok{
...
}
Check if the FILE1 implements the IStream interface, and if so, execute the {} statement.
9. Type query:
var v1 interface{} = ...
Switch V:=V1. (type) {
Case INT:
Case string:
...
}
10. Interfaces can be combined, consistent with the combination of classes.
11.interface{} can be used to define any type.


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.