go from entry to advanced notes

Make a note of running account the style of it. Used in the work go, but after all, is not the main language, with some places may not.

Business needs and must have a place to use the go, the recent plan to transform the existing c ++ service, which is used to replace part of the business go.

Recently read Xu Bo always go from the introductory to advanced. He made a water notes.

 

Based on these knowledge to write a bunch of code, more ugly, I will not put up ah.

 

# Knowledge Daquan

## 1 Initial language

The new, simple, fast, clear style, powerful standard library

2 ## basic syntax

Variable declarations, assignment

Anonymous variable

Data type: integer, float, boolean, string,
character,
sliced

Type Conversion

Pointer: Pointer type, slice

1 declare a pointer
2 new ()

Variable life cycle: stack, heap

Escape Analysis: Automatic variable allocation decisions, improve operational efficiency

1 Analysis escape -gcflags "-m -l"
2 address-escape analysis occurs
3 Principle
whether a variable is taken to the address
2 if the variable escape occurred

Operation of the supplied string

length, address-connection

Formatting

% v% + v% # v $ T %%% b% o% d% x $ X% U% f% p

constant const

Enumeration iota

Type alias and type definition

type NewInt int
type = int IntAlias

You can not add non-native type method

## 3 vessel: storing and organizing data

Array: length of contiguous memory area of the fixing

sections: the size of the contiguous space dynamically allocated

an array or slice generating
2 the make
. 3 Remove the append Copy:

Map

. 1 the make
2 Range
. 3 Delete
. 4 Clear, rely on garbage collection

sync.Map

. 1 Initialization
2 Store, the Load, the Delete
. 3 the Range

Container / List

. 1 initializes list.New ()
2 PushBack, PushFront
. 3 the Next

## 4 Process Control

if
for

for range【array slice string map channel】

switch fallthrough

goto break continue


## 5 Functions

Function first-class citizens: the value of the transfer, anonymous functions, closures, interfaces meet

Statement function

1 function supports multi-value return value
2 supports direct return variable

The structure is passed by value in the function

Function can be used as a value

Anonymous function

Function type that implements the interface, the function assigned to the interface

Closure: reference environment function +

Variable parameter

... interface {}

Statement defer execution delay

Error handling without error

type interface error Error {()} String

panic panic and recover


6 structure ##

new types of indicators or &

Definition of the structure

Examples of the structure

1 var v1 T
2 new(T)
3 &T{}

Member variable initialization structure

more than one initial value of
2 anonymous object initialization

Analog Constructor

Embedded analog parent constructor

method

func (receiver type) method name (parameter list) (return parameter) {}

The receiver method of

a finger receiver

The basic type of the same name defined type, a method of adding

Embedded type

1 member variables can directly access the built-in
2 field name is the name of its type

Built-in combination


## 7 Interface

Declare an interface, the interface naming conventions

Implement the interface conditions: 1 Format 2 are implemented exactly the same way

Relationship types and interfaces

Abstract service logic using the interface

Nesting Interface

Conversion between classes and interfaces: an interface type switch, switch interface type

t: = i (T).

} {Empty interface type interface

. 1 to the value storing empty interface
2 interfaces null value i. (Int)

Interface null value comparing

a compare result of different classes, dynamic values can not be compared

Branch empty class (interface {}). (Type)

## 8 package

GOPATH environment variable to provide a working directory project

More GOPATH

Creating package package

sibling files in a directory attributable to a 1 package
2 package name may be different from the directory
3 No main package does not output executable file

Export Identifier: uppercase

Import packages Import

. 1 XXX package alias name
2 anonymous imported packages _ "xxx"

Init initializes the package

1 on a packet
2 initialization sequence

Factory mode management structure of a plurality of packets


## 9 Concurrent

Create a coroutine go

Create a coroutine use anonymous functions

runtime.GOMAXPROCS () to set the number of cores


Channel Chan

the make (Chan XX)

Data transmission channel: Channel <- Data

Receiving channel data: data: = <- Channel

Data, OK: = <- CH
for Data: Range CH = {}

Unidirectional path transmission only: chan <-

Only the unidirectional channel receiver: <- chan

Unbuffered channel

Channel select multiplexer

time.After timer

time.NewTicker fixed timer

Close off the channel


go run -race detection competition


Synchronization of atomic

Mutex synchronization of sync.Mutex

sync.Mutex
sync.RWMutex


Synchronization of the waiting group sync.WaitGroup


## 10 reflected

Reflection is the ability to access and modify the program itself during program operation.

Reflection type object reflect.Type

reflect.TypeOf (A)

Reflection type Type, native type system

Reflection type Kind, type of ownership of the type

reflect.Elem Get a pointer to the type of element

Obtaining results suggest reflecting members

Field, (I) StructField
NumField () int
FieldByName (name) (StructField, BOOL)
FieldByIndex (index [] int) StructField
FieldByNameFunc (FUNC match (String) BOOL) (StructField, BOOL)

StructField

Name,PkgPath, Type, Tag, Index, Anonymous

StructTag

the Get (Key) String, the Lookup (Key) (String, BOOL)

reflecting the value of the object reflect.Value

use any value reflecting object packaging reflect.ValueOf (rawValue)

Get value from the reflectance value packaged

Interface () {} interface
Int (), Uint (), the Float (), Bool (), Bytes (), String ()

Field value using reflection members access structure

Field, (I) the Value
the NumberField ()
FieldByName (name) the Value
FieldByIndex (index [] int) the Value
FieldByNameFunc (FUNC match (String) BOOL) the Value

Empty reflecting object and the validity judgment

isNil, isValid

Using reflection value of the object to obtain the value of the variable [address, and then modify]

Elem () similar *
Addr () Similar &
CanAddr () BOOL
CANSET () BOOL

Object modification using reflection values related methods

SetInt, SetUint, SetFloat, SetBool,
SetBytes, SetString

Examples of the type created by the type of

1 reflect.New (typeOfA)

using reflection to invoke the function

funcValue.Call (xx)


## 11 compilers and tools

go build

-v package names
-p concurrent compilation
-a forced to rebuild
-race open race detection

go run

go install compile and install

go get

go test

file XX_test
method TestXX (t * testing.T)

test method specified

go test -v -run TestA xxxx_test.go

Terminate the test t.FailNow ()

Benchmark

Benchmark_Add (b * testing.B) bN
Go the Test -v -bench =. Xxxx_test.go

Custom time -bench -benchtime = 5s bench

test memory -bench = Alloc -benchmem xxx_test.go

The control timer

b.ResetTimer () resets
b.StopTimer () stops
b.StartTimer () Start

Go pprof performance analysis

tool mounting Graphviz graphics packages
2 runtime.pprof may be used, but less convenient
. 3 Go GET github.com/pkg/profile
. 4 Go Build
. 5 Go Tool pprof, XXX - PDF xx.pprof> xx.pdf

## and 12 to avoid the pit skills

### rational use of concurrency features

1 Understanding goroutine lifetime and then create goroutine

created, quit

2 Avoid using unnecessary channels in place

a channel in order to ensure goroutine concurrent access, also need to do a lock operation

3 reflection: the performance and flexibility of the double-edged sword

1 using native code, to avoid reflections
2 ahead cache reflection objects larger performance help
3 avoid using reflection function call, it needs time, ahead buffer function parameter list, and minimize the use of the return value

. 4 nil pointers can only be assigned to the interface and

the interface underlying type and data, that is are nil nil yes

Direct returns nil nil return is found


Multi hash value and the key index query

a hash value string rotation
2 for keys


The elegant handle TCP stick package

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

Guess you like

Origin www.cnblogs.com/beckbi/p/11619288.html