1 channel implementation CSP model
2 Memory allocation: Tcmalloc
3 Dynamic library Buildmode function???
4 lacks the true meaning of the debugger???
5 Dependencies on package management issues???
6 The compiler treats unused local variable definitions as errors
The 7 function can return the function type Func test () func (int) {
return func (x int) {
println ("x:", X)
}
}
8 defer defines deferred invocation, which ensures that the function is called before the end, regardless of the error
9 Ok-idiom (a) mode: A Boolean value named OK is used in multiple return values to mark the operation as successful, because many operations return 0 values by default, so additional instructions are required
10 Anonymous fields in structs, instances of structs can invoke methods and properties of anonymous fields directly
11 interface using Duck type mode
A CSP model that implements communication instead of shared memory for channel and Goroutine
1 variables in a computer are one or more pieces of memory used to store data, the type determines the length of the variable memory and the storage format, so we can only modify the variable value cannot modify the type
2 memory allocation occurs at run time, the compiled machine code does not use the variable name but uses the memory address directly to access the target data, so the coding phase uses the easy-to-read variable name
3 Conventions recommend organizing multi-line variables in a group definition var {x, y int}
4 short declarations are typically used for functions that have multiple return values, and if a local variable is defined in a statement such as a for switch
5 unused local variables compile error, global variable not error
6 naming suggested letters or underscores start with multiple alphanumeric and underscore combinations, local variable precedence short name
7 Constants The preprocessing phase is expanded into instruction data, which allocates storage memory at run time. (so constant cannot be addressed, no address)
8 Byte is an alias of Uint8 Rune is an alias of int32 that can be assigned directly to each other without the need for type conversion
9 having the same underlying structure does not mean that it belongs to an alias
New assigns a 0 value memory return pointer to the specified type; make is a reference type-specific creation function (memory allocation and property initialization)
More than 11 type can be combined to initialize
12 Unnamed Types: arrays, slices, dictionaries, channels, etc. types that are related to attributes of a specific element type or length can be changed to a named type by using the type
13 different types are different for unnamed type struct tags, and the field order is different.
1 program = algorithm + data algorithm: The process of solving the problem, small to the addition of instructions large to the distributed cluster
2 exponentiation and absolute value operations in the POW and abs of the math package
3 self-increment reduction can only be used as a standalone statement
4 pointer is the entity allocates memory space, memory address is the unique number of each byte cell in memory
5 pointer type points to the same address or nil equals, but cannot add minus and type conversions
6 unsafe. Pointer converts the pointer to uintptr for addition and subtraction operations, but may cause unauthorized access
7 pointers cannot be used with->
8 composite type initialization, must contain the type label; the left curly brace must be at the end of the type; multiple members are separated; the right side of the multiline must be a comma or curly brace
9 switch does not need to explicitly perform a break, but you want the sequential execution to explicitly execute Fallthrough
The range iteration is copying data
One goto can only jump to a sibling code, not across levels
The break is used for a switch for select to terminate the entire statement block execution
Continue only for a for loop, terminating subsequent logic immediately into the next round of loops
The 1 function does not require a predecessor declaration, does not support naming nested definitions, does not support overloading with the same name, does not support default parameters, supports variable-length parameters, supports multiple return values, supports anonymous functions and closures
2 function type supports nil judgment only and does not support other comparison operations
3 returning a local variable pointer from a function is safe, and the compiler determines whether to allocate memory on the heap by escaping analysis, so the parameter minimizes the value copy
4 function suggested naming rules: verb + name; avoid unnecessary abbreviations (printerror better than printerr), avoid using type keywords, use idioms (init for initialization, Is/has return Boolean), and use antonyms to name the opposite function
5 Whether it is a pointer, reference type, or its Tianya type parameter, it is a value copy pass, which differs from the target object of the copy.
6 The disadvantage of passing the pointer is to lengthen the declaration period of the variable, and may cause him to allocate to the heap to increase performance consumption
7 function parameters are valid inside the function, scope is the entire function inside
8 Variable parameter func test (a ... int) {} test (a[:] ...)
9 problem with named return value: The newly defined local variable with the same name causes the same name to be obscured: xx is shadowed during return;
10 Closure Anonymous functions can use the context of the data in the environment (final data)
11 deferred call defer is commonly used for resource release unlock error handling, etc. first-in and after-out. Latency calls are expensive, and performance requires high-pressure algorithms to avoid using them as much as possible
The error is the interface type
Panic will trigger the function interrupt execution defer, use recover to capture panic submitted error object in defer (recover can only be performed in defer)
14 + Panic Only the last one is captured
Runtime/debug. Printstrack () can print the complete stack information
16 Non-recoverable errors that cause the system not to work correctly use Panic (file system not privileged operation, service port occupied, database not started, etc.)
1 string is a sequence of immutable bytes (byte) that can be used to get the length, not the cap; ' support cross-line; Allow byte array access, single byte array not allowed to take address
2 When you point to an array with a slice, the underlying still points to the string
3 range traversal can print out Chinese characters, Len traversal of Chinese characters is garbled
4 append can be added to []byte = "var bs []byte Bs=append (BS," abc "...)
5 string addition operations reallocate memory each time, building large string performance is very poor; Method 1:strings. The Join method 2:bytes. Buffer Small string concatenation using FMT. Sprintf Text/template, etc.
6 UTF8. Runecountinstring (s) to get string lengths with Chinese characters instead of Len
7 length is an array of type components, elements of the same length of different arrays are not the same type
8 Multi-dimensional arrays, only the first dimension support ... [...] [10]
9 If the element supports the = = = operation, the array also supports
10 Array value type
11 slices: Not a dynamic array or array pointer, internally referencing the underlying array by pointers, and setting related properties to limit data read and write operations to the specified area.
The 12 slice itself is a read-only object, and the right half-open interval array that works like an array pointer must be addressable
Type Slice struct{
Array unsafe. Pointer
Len Int
Cap INT
}
When a 13 slice references an array, the slice pointer points to the array address, the access is out of bounds, the array is appended, and the address is reassigned when the length is greater than the CAP, and the slices and arrays are independent of each other append
The 14-slice var a[]int is nil, only for him to initialize, but still allocates memory, and a[:] still nil.
15 If a slice consumes a small amount of data from a large array for a long time, it is recommended that the slices be assigned addresses separately to allow large arrays to be released early
16 The string can be copied directly to []byte = B:=make ([]byte,3) n:=copy (b, "ABCDEFHG") =>n=3,b=[97 98 99]
17 The dictionary key must support = = = = number, string, pointer, array, struct, interface
If v,ok:=m["D"];ok{exists} use Ok-idiom mode to determine if key exists
Delete (M, "D"), remove the nonexistent key without error
Map using range iteration in each order
Map is designed to no addressable, all members cannot modify value (if value is a struct or an array, etc.); Improved Method 1: First obtain the full value, modify and then assign the value back; method 2:value takes a pointer type
Because value is a pointer, all the data that the pointer points to can be modified by the pointer.
Map concurrent operation, a task for the map write operation, other tasks on the map read and write delete will cause the process to crash, available sync. Rwmutex implementation Synchronization (do not use defer)
The map object itself is a pointer wrapper, which does not need to take an address
When the map is created, the same as slice to pre-allocate enough addresses to reduce unnecessary memory allocations and re-hashing operations during expansion =>make (map[int]int,1000)
25 for a large number of small objects, you should use a dictionary to store key-value data copies instead of pointers, thus reducing the amount of scanned objects to reduce garbage collection time.
26 dictionaries do not shrink memory, appropriate replacement of new objects is necessary ...
27 structure recommended naming initialization to prevent the expansion of the structure of the Times wrong
28 Anonymous Structure
u:=struct{
Name string
}{
Name: "XXX",
}
29 The structure supports equality operations only when all members support the = = operation
30 the anonymous dictionary implicitly uses the name of the field as a type, which can be used to directly consume members of an anonymous field, but must be initialized as a separate field. (An implicit name does not include a package name, but an implicit field is an external type)
31 any named type other than the multi-level pointer to the interface pointer can be an anonymous type
32 cannot speak the underlying type and its pointer type are also anonymous because their anonymous name is the same
33 The field label is the metadata that is described for the field, is part of the type, and can be used to obtain label information during run time, usually as a format check and database relationship mapping, etc.
p1:=p{
Name: "XXX",
Sex:1,
}
V:=reflect. ValueOf (p1)
T:=v.type ()
for I,n:=0,t.numfield (); i<n;i++{
Fmt. Printf ("%s:%v\n", T.field (i). Tag,v.field (i))
}
Reflect. Structtag provides a more complete function
1 Front-facing instance receive parameter-receiver
2 receiver is the underlying type and will be copied, and the pointer type must be able to obtain the instance address
3 Receiver type selection: Do not modify small objects or fixed values with T; reference types, strings, functions, and other pointers wrap objects with T; modify instance state with *t; Include synchronization fields such as mutexes with *t, large objects or uncertain situations with *t;
4 methods of anonymous types also have attributes that are masked by the same name. (can achieve similar overwrite operation)
The set of methods for 5 T is receiver T;*t's method set is receiver T+*t
6 Anonymous embedding s,t contains receiver S; anonymous embedding *s,t contains receiver s+*s; anonymous embedding S or *s,*t all contain receiver s+*s;
7 method sets only affect interface implementations and method expression conversions. Anonymous fields are prepared for the method set
1 Chan, one-time event using Chan's close more efficient
Send data to Close's Chan panic
Receive data from closed Chan to return cached data or 0 values
Regardless of the method, nil channel will block
2 synchronization issues should be manipulated with locks or atomic variables
Win avoid using defer when performance requirements are high unlock
Better performance with Rwmutex when reading and writing concurrency
Read and write protection for individual data is recommended for use with read/write locks
Rigorous testing to open data competition checks whenever possible
3 channels tend to resolve concurrent processing architectures at the logical level
4 locks are used to protect data within a local scope