Go Language Learning Note 2

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

2. Basic lexical of Go language

The language symbol of the go language, also known as lexical elements, consists of 5 classes: identifier (identifier), keyword (keyword), operator (operator), delimiter (delimiter), and literal (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.

Attention:

  1. In the Go language code, each identifier must be declared before it is used.
  2. A declaration binds a non-null identifier to a constant, type, variable, function, or code package.
  3. Duplicate declarations of the same identifier (except for assignment statements) are not allowed in the same code block.
  4. This rule is required for identifiers in a source file and in a code package.
  5. 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.

A qualified identifier can be used, and it needs to meet two prerequisites:

  1. The code package to be accessed must be imported beforehand;
  2. The identifiers in this code package must be exportable.

An exportable identifier also needs to meet two prerequisites:

  1. 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;
  2. 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:

  • The name of all the base data types.
  • Interface type Error
  • Constants True,false and Iota
  • The names of all the built-in functions are append, caps, 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 following 3 classes are used in the Go Language code:

    The
    1. represents the various literal values of the underlying data type. For example, 12E-3 that represents the value of a floating-point number type.
    2. Constructs type literals for various custom composite data types. For example, the following represents a custom structure type named person:

      type  person  struct {name  string  age  uint8  address  string }    
    3. Represents the compound literal of the value of the composite data type, which is used to construct the type struct (struct), array (array), The value of the 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.

//表示结构体类型值,有重复的键 Name"Huazie""21""Unknown"}//表示字典类型值,有重复的键 Agemap[string]string"Huazie""21""21"}//表示切片类型值,有重复的键 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.

varstring

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

typestring

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.

Attention:

  • 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 2 operators :

  1. &^ implementation of the bitwise CLEAR operation, the bitwise clear is based on the second operand of the binary value of the first operand of the binary value of the corresponding 0 operation, if the second operand of a bits on an array of 1, the first operand of the corresponding bits on the value set 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.
  2. ^ 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     //无符号整数的一元按位异或操作000000011111111111111110//对应的二进制数运算

    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//有符号整数的一元按位异或操作000000011111111111111110//对应的二进制运算

    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.

  3. 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 := <-chv2 = <-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 = <-chv, 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.

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.