Go Bible Notes-Chapter II

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



2.1 Naming
1) a name must begin with a letter (Unicode letter) or underscore, followed by any number of letters, numbers, or underscores.
Uppercase and lowercase letters are different.


2) keywords are 25; keywords cannot be used for custom names and can only be used in specific grammatical structures.
Break default Func Interface Select
Case defer go map struct
Chan Else goto package Switch
Const Fallthrough If range type
Continue for import return Var


3) There are more than 30 predefined names, such as int and true, which correspond to the built-in constants, types, and functions.
Built constant: true false iota Nil


Built-in type: int int8 int16 int32 int64
UINT uint8 uint16 UInt32 UInt64 uintptr
float32 float64 complex128 complex64
BOOL Byte Rune string error


Built-in functions: Make Len cap new append copy close Delete
Complex Real Imag
Panic recover
These internal pre-defined names are not keywords, and you can reuse them in the definition.


4) Inertia Usage
If a name starts with a capital letter, it will be exported, meaning it can be accessed by an external package.
The name of the package itself is usually in lowercase letters.
Try to use a short name.
It is recommended to use the "camel" name.
Acronyms such as ASCII and HTML avoid the use of mixed case, which may be called Htmlescape, Htmlescape, or escapehtml, but not escapehtml.




2.2 Statement
1) Four types of declaration statements: VAR, const, type, and Func, respectively, corresponding to the declarations of variables, constants, types, and function entity objects.


2) Basic composition of each source file
Start with the declaration statement of the package, stating which package the source file belongs to.
The package declaration statement is followed by an import statement that imports dependent other packages, followed by a package-level type, variable, constant, and function declaration statement.


3) The Order of the declaration statements of various types, variables, constants, and functions at the package level does not matter




2.3 Variables
1) Variable declaration format
var variable name type = Expression
You can omit one of the types or expressions. The type is omitted, the type is deduced according to the expression, and the ellipsis expression is initialized to the 0 value of the corresponding type.
0 value of type
Numeric type 0
Boolean type False
String type empty string
Interface or reference types (including slice, map, Chan, and functions) nil
An aggregate type, such as an array or struct, each element or field is a 0 value of the expected type.


Declare multiple variables at the same time
var I, j, K Int//int, int, int
var b, F, S = True, 2.3, "four"//bool, float64, String


2) variables declared at the package level are initialized before the main entry function executes


3) Short Variable declaration
Can only be used in functions
I: = +/An int


You can initialize a set of variables, which are generally used to improve code readability, such as the for, if initialization conditions.
I, J: = 0, 1


In a short variable declaration statement, the left variable must declare at least one new variable, or it cannot be compiled.
Assign a value to a variable that has already been declared, if it is in the same lexical domain, and if it is a parent lexical domain, a new override ancestor variable is generated, which can cause strange bugs


4) pointer
A pointer corresponds to the location where the variable is stored in memory. Not every value will have a memory address, but there must be a corresponding memory address for each variable.


&x expression (takes the memory address of the x variable)


A value of 0 for any type of pointer is nil. The pointers can be tested for equality only if they point to the same variable or are all nil.


5) New
The expression new (t) creates an anonymous variable of type T, initializes a 0 value of type T, then returns the address of the variable, and returns a pointer of type *t.


6) A variable of size 0
struct{} or [0]int64
Be careful to use a type of size of 0, because if the size of the type is 0 nice, it may cause the go language of the automatic garbage collector to behave differently, see Runtime for details. Setfinalizer function Related Documents


7) Variable life cycle
For variables declared at the package level, their life cycle is consistent with the entire program's operating cycle. The declaration period for a local variable is dynamic: start with a declaration statement that creates a new variable each time, until the variable is no longer referenced.


8) Variable memory allocation
The compiler automatically chooses to allocate storage space on the stack or on the heap for local variables, but this choice is not determined by the way Var or new declares variables.


2.4 Assigning values
1) Tuple Assignment
Allows you to update values for multiple variables at the same time. Before assigning a value, all expressions to the right of the assignment statement are evaluated first, and then the value of the corresponding variable on the left is updated uniformly.
Swap variables
X, y = y, X
A[i], a[j] = A[j], a[i]
F, err = OS. Open ("foo.txt")//need to ensure that the function return value is consistent with the number of left variables


V, OK = m[key]//Map Lookup
V, OK = x. (T)//Type Assertion
V, OK = <-ch//channel receive


For cases where the value produces a result, the map lookup fails with a value of 0, a runtime panic exception is sent when the type assertion fails, and a 0 value is returned when the channel receives failure (blocking is not considered a failure).




2.5 types
1) A type declaration statement creates a new type name, and the existing type has the same underlying structure.
Type name underlying type
Type Celsius float64//Celsius temperature
Type Fahrenheit float64//Fahrenheit temperature


The underlying data type determines the internal structure and expression, as well as the ability to support built-in operators like the underlying type. The arithmetic operation behavior of Celsius and Fahrenheit types is the same as the underlying float64 type.


2) Type conversion
For each type T, there is a corresponding type conversion operation T (x).
A transition operation is allowed only if the underlying underlying type of the two types is the same, or both are pointer types that point to the same underlying structure, which only changes the type without affecting the value itself.


3) for Chinese characters, Unicode flags are treated as lowercase letters, so the Chinese naming is not exported by default;




2.6 Packs
1) By convention, the name of a package is the same as the last field of the package's import path


2) Package Notes
Only comments that follow the package declaration for each source file are package comments.
In general, the first sentence of the package comment should first describe the package's functional outline.
A package usually has only one source file that has a package comment.
If there are multiple package annotations, the current document tool links them to a package comment based on the order of the source filenames.
If the package annotation is large, it is usually placed in a separate doc.go file.


3) Initialization of the package
If the package contains more than one. Go source file, they are initialized in the order that they are sent to the compiler, and the Go Language builder first sorts the. go file according to the file name, and then calls the compiler to compile.


Each file can contain multiple init initialization functions, such that the INIT initialization function is similar to the normal function except that it cannot be called or referenced.
Init initialization functions in each file are automatically called in the order in which they are declared when the program starts executing.


Each package is initialized in the order in which the declarations are imported, and each package is initialized only once, in the context of resolving dependencies.
Initialization is done from the bottom up, and the main package is finally initialized. In this way, you can ensure that all the remaining packages have been completed before the main function is executed.




2.7 Scopes
1) The scope of the declaration statement refers to the range in which the name can be used effectively in the source code.


2) control stream, which is the type of label followed by a break, continue, or Goto statement, is the scope of the function level.


3) If a variable or constant references itself recursively, a compilation error is generated. Functions and types are not.


4) The custom of the go language is to handle errors in the IF and return directly, which ensures that the normal execution of the statement does not require code indentation.





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.