2. Basic lexical of Go language
The language symbols of the go language are also known as lexical elements, including 5 classes: Identifiers (identifier), keywords (keyword), operators (operator), delimiters (delimiter), and literals (literal). In general, space characters, horizontal tabs, carriage returns, and line breaks are ignored unless they are part of a delimiter between multiple language symbols. There is no need to insert semicolons in the Go language, and when necessary, the go language automatically inserts semicolons into the code for statement separation.
The Go language code consists of a number of Unicode characters, all the source code of the go language must be encoded by the Unicode encoding specification UTF-8 encoding format (that is, the written go language source file must be UTF-8 encoded format).
2.1 Identifiers
The identifier for the Go language is a sequence of characters consisting of several letters (Unicode encoded), underscores, and numbers, and the first character of the character sequence must be a letter.
Note: in the Go language code, each identifier must be declared before it is used. A declaration binds a non-null identifier to a constant, type, variable, function, or code package. Duplicate declarations of the same identifier (except for assignment statements) are not allowed in the same code block. This rule is required for identifiers in a source file and in a code package. The scope of a declared identifier is the same as that of the code block directly to which it belongs.
Strictly speaking, a code package declaration statement is not considered a declaration. Because the code package name does not appear in any one scope. The purpose of a code package declaration statement is to identify whether a number of source files belong to the same code package, or to specify the default code package reference name when importing a code package.
Qualified identifiers are used to access variables or types in other code packages. For example, when I need access to a constant called O_rdonly in the code package OS, I need to write this to the OS. O_rdonly.
Qualifying identifiers can be used and need to meet two prerequisites: The code package to be accessed must be imported beforehand; The identifiers in this code package must be exportable.
An exportable identifier also needs to meet two prerequisites: the first character in the identifier name must be uppercase (the Go language determines access to the identifier based on the case of the first character in the identifier name, and when the first character of the identifier name is uppercase, its access is "public", That is, the identifier can be accessed by qualifying identifiers by any code in any code package, and when the first character of the identifier is lowercase, its access is "package-level private", which means that only code that is in the same code package as the identifier can access it; The identifier must be the name of a variable or type that is declared in a code package, or the name of a field or method that belongs to a struct type.
Predefined identifiers for the Go language: Names of all base data types. Interface type Error constants True,false and iota all the names of the built-in functions, namely append, cap, close, complex, copy, delete, imag, Len, make, new, panic, print, println, real and recover.
There is a null identifier in the go language, which is represented by an underscore, and is typically used in a declaration that does not need to introduce a new binding. For example, when we want to execute only the initialization function in a code package without needing to use any of the program entities in this code package, we can write the following import statement:
Import _ "Runtime/cgo"
Where "Runtime/cgo" represents an identifier for a standard library code package.
2.2 Key Words
Keywords (also known as reserved words) are sequences of characters that are reserved by the programming language and are not used by programmers as identifiers.
category |
Key Words |
Program Declaration |
Import, Package |
Program entity declaration and definition |
Chan, const, Func, interface, map, struct, type, var |
Program Control process |
Go, select, break, case, continue, default, defer, else, Fallthrough, for, Goto, if, range, return, switch |
In the go language, the declaration and definition of a program entity is based on the system of its data type. For example, the keyword Chan, func, interface, map, and struct, respectively, in the go language of the composite data type channel (channels), function (functions), Interface (interface), Map (dictionary) and struct (struct) correspond.
A total of 15 key words for the program control process. Where go and select, these two are mainly used for go language concurrent programming.
2.3 literal
The literal used in the Go language code has the following 3 classes: Various literals representing the values of the underlying data type. For example, 12E-3 that represents the value of a floating-point number type.
Constructs the type literals of various custom composite data types. For example, the following represents a custom struct type called Person:
Type person struct {
Name string
age uint8
Address string
}
A compound literal representing the value of a composite data type used to construct values of type struct (struct), array (array), Slice (slice), and map (dictionary). For example, the following literal is used to represent the value of a struct type with the name of person above:
person {
Name: ' Huazie ', age
: "+",
Address: "Nanjing, China"
}
Note:
Each evaluation of a compound literal causes a new value to be created. Therefore, the value of a new person type is created as soon as the compound literal is evaluated at a time.
The go language does not allow duplicate keys to appear in a compound literal variable of this class. The following are errors that cannot be compiled because the keys are duplicated.
Represents struct type value with duplicate key name person {name: ' Huazie ', Age: ' + ',
name: ' Unknown '}
//= Dictionary type value, with duplicate key age
map[ string]string{Name: "Huazie", Age: "+", Age: "+"}
//Represents the slice type value, with duplicate key 0
[]string{0: "0", 1: "1", 0: "1"}
2.4 Types
A type determines the set of values and the actions that can be exerted on those values. A type can be specified by a type name or type literal, divided into a base type and a composite type, and the name of the base type can represent itself.
var bookname string
A variable of type string (one of the base types), called BookName, is declared above.
Other basic types (pre-defined types) are bool, Byte, Rune, Int/uint, Int8/uint8, Int16/uint16, Int32/uint32, Int64/uint64, float32, float64, Complex64 and complex128. Other basic types other than bool and string are also known as numeric types.
A composite type is typically composed of several (and also 0) other defined types. Composite types have channel (channels), function (functions), Interface (interface), Map (dictionary), struct (struct), Slice (slice), array (array), and pointer (pointers).
The types in the go language can also be classified as static types and dynamic types. The static type of a variable refers to the type given in the variable declaration. Most types of variables have only static types. The exception to the variable of the interface type is that it has a dynamic type in addition to the static type (the interface type is described later).
Each type will have a potential type. If the type is a predefined type (that is, a base type), or a composite type constructed from a type literal, its potential type is itself. A potential type such as a string type is a string type, and the potential type of the person type above is the person. If a type does not belong to the above, the potential type of this type is the latent type of that type in the type declaration.
Declare a custom type as follows
Type MyString string
If you can think of type mystring as an alias type of type string, then the potential type of the mystring type is the string type. The rune type in the Go language base data type can be considered an alias type of the UInt32 type, and its potential type is uint32.
Note: type mystring and type string are two different types. You cannot assign a value of one of these types to a variable of another type. The alias type differs from its source type only on the name, and their internal structure is consistent; The following types convert expressions are valid: MyString ("abc") and String (MyString ("abc")). This type conversion does not create a new value.
A potential type of a type has transitivity, as follows:
Type istring MyString
The potential type of type isstring is the string type.
This declares a type, as follows:
Type mystrings [3]string
Note: The potential type of type mystrings is not [3]string. [3]string is neither a predefined type nor a composite type constructed from a type literal, but an array type with an element type of string.
According to the above definition, the potential type of the mystrings type is [3]string's potential type string.
The go language dictates that the potential type of an array type determines which type of element can be stored in a variable of that type.
2.5 operator
An operator is a symbol used to perform a particular arithmetic operation or logical operation. (This is not explained in detail, similar to the C language operator), but there is no ternary operator in the go language, so it must be a two-dollar operator besides the unary operator. The go language has a total of 21 operators, including arithmetic operators, comparison operators, logical operators, address operators, and receive operators.
symbols |
Description |
Example |
|| |
Logic or operation. Binary, logical operator |
true | | False//Expression result is true |
&& |
Logic and operations. Binary, logical operator |
True && false//expression result is false |
== |
Equal judgment operation. Binary, comparison operator |
"ABC" = = "abc"//Result is true |
!= |
Unequal judgment operation. Binary, comparison operator |
"ABC"! = "ABC"//Result is true |
< |
Less than the judgment operation. Binary, comparison operator |
1 < 2//expression result is true |
<= |
Less than or equal to. Binary, comparison operator |
1 <= 2//Expression result is true |
> |
Greater than the judgment operation. Binary, comparison operator |
3 > 2//Expression result is true |
>= |
Greater than or equal to. Binary, comparison operator |
3 >= 2//Expression result is true |
+ |
The sum, the unary is two yuan, the arithmetic operator |
+1//result is 1 (1+2)//result is 3 |
- |
For the difference, a dollar is two yuan, arithmetic operators |
-1//result is-1 (1–2)//result is-1 |
| |
Bitwise OR operation, two-dollar, arithmetic operator |
5 | 11//The result of the expression is 15 |
^ |
Bitwise XOR, unary is two yuan, arithmetic operator |
5^11//result is 14 (^5)//result is-6 |
* |
Quadrature or value, one yuan, two yuan, arithmetic, address |
*p//Take value operation |
/ |
Business operation, two yuan, arithmetic operator |
10/5//The result of an expression is 2 |
% |
For remainder operation, two yuan, arithmetic operator |
12% 5//The result of an expression is 2 |
<< |
Bitwise left SHIFT, two-dollar, arithmetic operator |
4 << 2//The result of the expression is 16 |
>> |
Bitwise RIGHT SHIFT operation, two-dollar, arithmetic operator |
4 >> 2//The result of the expression is 1 |
& |
Bitwise AND operation, unary, two yuan, arithmetic, address |
&V//Fetch address operation |
&^ |
Bitwise CLEAR operation, two-dollar, arithmetic operator |
5 &^ 11//The result of an expression is 4 |
! |
Logical non-operation, unary, logical operator |
!b//If B is true, the result is false |
<- |
Receive operation, unary, receive operator |
<-CH |
Note: Assuming that the above CH represents a channel type value with an element type of byte, then <-CH represents an operation that receives a byte type value from Ch.
focus on 3 operators : &^ implementation of the bitwise CLEAR operation, the bitwise clear is based on the binary value of the second operand to the first operand of the binary value of the corresponding 0 operation, if the second operand of an array on a BITS is 1, Set the number on the corresponding bits of the first operand to 0. Otherwise, the number on the corresponding bits of the first operand does not change. Such an operation does not change the original value of the first operand, only the result value is computed based on the binary value of the two operands. This allows you to understand that the result of the above 5 &^ 11 is 4.
^ As a unary operator, in two cases:
(1). The operand is an unsigned integer type, and using this operation is equivalent to a bitwise XOR OR operation of $ two for the maximum value of the operand and its integer type, as follows:
^uint8 (1) = 254 //unsigned integer bitwise XOR or Operation
00000001 ^ 11111111 = 11111110//corresponding binary number operation
As above, the built-in function uint8 converts an integer literal to a value of type uint8, which guarantees that the unique operand of the unary operator ^ must be a value of an unsigned integer type.
(2). The operation is a signed integer type, which is equivalent to two meta-bitwise XOR of the operand and-1. For example:
^1 =-2//Unary bitwise XOR OR operation of signed integers
00000001 ^ 11111111 = 11111110//corresponding binary operation
Note: The binary values of the above operands are in complement notation, and by default the integer literal is signed, so the operand 1 in (2) does not need to be displayed using the built-in function int8.
The <-receive operator, which is used only for channel type values. When using, you need to pay attention to two points:
(1). An expression that receives a value from a null value (that is, nil) from a channel type will be blocked forever.
(2). Receiving a value from a channel type value that has been closed will always succeed and immediately return a 0 value of its element type.
An expression consisting of an operand of the receive operator and the channel type can be used directly for variable assignment or initialization, as shown below (as explained in the assignment statement)
V1: = <-ch
v2 = <-ch
Special token = used to assign a value to a variable or constant that has been declared.
Special tags : = is used to assign a variable at the same time as it is declared, and can only be used within the function body.
Also as follows:
V, OK = <-ch
V, OK: = <-ch
When you assign or initialize two variables at the same time, the second variable will be a Boolean type value. This value represents the success or absence of the receive operation. If this value is false, it means that the channel has been closed. (Detailed description of the channel type will be explained later.)
Operator Precedence
Priority Level |
operator |
5 |
*/% << >> & &^ |
4 |
+ - | ^ |
3 |
= = = < <= > >= |
2 |
&& |
1 |
|| |
2.6 Expressions
Basic Expressions
(1) The use of operands to express;
(2) Use type conversion to express;
(3) using the built-in function call to represent;
(4) A basic expression and a selection symbol constitute the selection expression;
For example, if a field F exists in a struct type, we can use a selection symbol on the variable x of the struct type to access the field F, the X.F. Where,. f is a selection symbol. Note: If the value of this variable x cannot be nil. In the go language, nil is used to denote null values.
(5) A basic expression and an index symbol to form an index expression;
An index symbol consists of a narrow expression (consisting only of operators and operands) and an outer square bracket, such as []int{1,2,3,4,5}[2] is an index expression.
The Go language allows the following assignment statements:
V, OK: = A[x]
As above A is a dictionary type, x is the key of the dictionary. The result of the index expression is a pair of values, not a single value. The type of the first value is the element type of the dictionary type, and the second value is the Boolean type. A Boolean value bound to the variable OK represents whether a key-value pair with the X key is included in the dictionary type A. If you include such a key-value pair in a, the value assigned to the variable OK is true, otherwise it is false.
Note: While the value of variable A of the dictionary type is nil, the evaluation expression A[x] does not cause any errors, but assigning a value to a[x] in this case causes a run-time panic (Go language exception).
(6) A basic expression and a slice symbol to form a slice expression;
The slice symbol consists of 2 or 3 narrow-sense expressions and the outer brackets, which are separated by a colon. The slice symbol acts like an index symbol, except that the index symbol is for a point and the slice symbol is for a range. For example, to remove the second to fourth element of a slice []int{1,2,3,4,5}, you can use the expression []int{1,2,3,4,5}[1:4] of the slice symbol, which is also a slice.
The slice expression A[x:y:z],a is the action object of the slice symbol [x:y]. where x represents the lower index of the slice element, Y represents the upper-bound index of the slice, and z represents the upper-bound index of the slice's capacity. The constraints are as follows:
0 <= Element Nether index <= element upper bound index <= upper bound index <= the capacity of the Operation object
The value of set A is []int{1,2,3,4,5}, then the slice expression A[:3] is equivalent to A[0:3], because the default value for the element nether index of the slice symbol is 0, and the default value of the index to the upper bound of the corresponding element is the length or capacity value of the operand, that is, the slice expression a[3:] equals to a[ 3:5]. Similarly, the slice expression a[:] is equivalent to copying the value represented by a and taking the copy as the evaluation result of an expression.
Note: The UTF-8 encoding format represents a Chinese character in 3 bytes, and the slice operation is for bytes.
If there is a "go concurrency Programming" string type of variable A, then the result of the slice expression A[1:3] is not "O and", and the result of A[1:5] is "O and".
(7) A basic expression and a type assertion symbol;
The type assertion symbol is prefixed with a period of English and followed by a type name or type literal enclosed in parentheses. Type assertion symbols are used to determine whether a variable or constant is an expected type, and to take a different response depending on the result of the decision. For example, if you want to determine whether a variable num of type int8 is of type int, you can write the expression: interface{} (num). (int).
For an expression x and a type T that evaluates to an interface type value, the corresponding type assertion is:
X. (T)
The function of this expression is to determine whether the "X is not nil and the value stored therein is of type T" is true.
If T is not an interface type, then X. (t) determines whether the type T is a dynamic type of x (the dynamic type of a variable is the actual type of the value stored in it during the run), and the actual type must be an implementation type of the type declared by the variable, otherwise it is not possible to store this type of value in the variable. So type T must be an implementation type of type X, and only the interface type can be implemented by other types in the go language, so the evaluation result of x must be a value of an interface type.
So the above expression interface{} (num). The meaning of the expression interface{} (num) in (int) is to convert the variable num to a value of type interface{} (that is, its result value is an interface type), which exactly matches the previous definition.
knowledge point: interface{} is a special interface type that represents an empty interface. All types are its implementation types.
You can also use a type assertion when assigning or initializing a variable, as follows:
V, OK: = x. (T)
When a type assertion expression is used to assign two variables at the same time, if the type assertion succeeds, the first variable is assigned the evaluation result of an expression x that has been converted to type T, otherwise the first variable is assigned a value of type T 0. The Boolean type is assigned to the variable OK, which reflects the success (true) or not (false) of the type assertion.
Note: in this scenario, a run-time panic is not raised even if the type assertion fails.
(8) A basic expression and a call symbol.
The calling symbol is only for functions or methods. The basic expression that is combined with the calling symbol is not an identifier that represents the name of the code package (or its alias), or the name of a method that represents a struct type. The call symbol consists of a full period prefix and a list of arguments enclosed in parentheses, separated by commas between multiple argument lists. For example, the basic expression OS. Open ("/etc/profile") represents a call to the function open in the code package OS.
variable length parameters
If the number of arguments that can be accepted by the function f is not fixed, then the function f is a function that can accept variable length parameters, referred to as the variable parameter function. In the go language, there will always be a variable-length parameter at the end of the parameter list of the variable parameter function, the type declaration of the variable-length parameter is like ... T. The go language creates a slice type value each time the function f is called and uses it to store the actual functions. The length of this slice type value is the number of actual arguments that are bound to the variable-length parameter in the current invocation expression.
The variable parameter function appendifabsent is declared as follows (the function body is omitted):
Func appendifabsent (s []string, T ... string) []string
The invocation expression for this function is as follows:
Appendifabsent ([]string ("A", "B", "C"), "C", "B", "a")
Where the tile type value bound to the variable parameter T is []string{"C", "B", "A"}, the actual parameters "C", "B" and "a" are included.
You can also assign the value of a slice type with an element type T directly to ... Variable-length parameters of type T, such as downward use:
Appendifabsent ([]string ("A", "B", "C"), []string ("C", "B", "a") ...)
Or if there is a variable s for the slice type of the element type stirng, such as a downward use:
Appendifabsent ([]string ("A", "B", "C"), S ...)
The go language does not specifically create a slice type value to store the actual parameters in cases where a variable of the slice type is assigned to a variable-length parameter. Because such a slice type value already exists, the value of the variable long parameter T is the value of the variable S.
The basic lexical interpretation of the go language is over, and the next step is to talk about the data types of the go language.
Finally, a well-known open source framework for Go language (each with one attached) is attached:
Beego: a homemade HTTP framework. We can use it to quickly develop a variety of applications. Official website: http://beego.me.