Introduction Go LanguageGo is an open-source programming language designed to make it easy for people to build simple, reliable, and efficient software. Go is sometimes referred to as the "Class C language" or "C 21st century". From c, go integrates expression syntax, control flow statements, basic data types, parameter passes by value calls, pointers, but more importantly, inherits the program that C emphasizes to compile into efficient machine code, and naturally matches the abstraction mechanism provided by the operating system.
Program StructureA go program is saved in one or more files that are later prefixed with. Go. Each file contains the package declaration at the beginning to specify which package the file belongs to. The package declaration is followed by an import declaration, which is used to import the library in the program. The import declaration is followed by the package level (Package-level) declaration, which includes types, variables, constants, and declarations of functions, and package-level declarations are visible in the same file and other files in the same package. The variable declared in the function is a local variable and is visible only in the function. The main function is the entry for the program.
Example:
Package main// packet declaration
import "FMT" //import declaration
Const PI = 3.14// package-level Declaration
Func Main () { ///Main is also package-level Other declarations
var f = 123.456 //Partial declaration
FMT. Printf ("f =%g\n", f)
}
variables and Constants identifiersNaming in the go language is no different from other languages: a combination of letters, numbers, underscores, but the first character cannot be a number. Names in the go language are case-sensitive. You cannot use a keyword as a name. There is no limit to the name length, but the shorter the better in Go tradition. The wider the visibility, the more difficult it is to define the longer the name. Go is used to name the hump. For example: Parserequestline If the name contains an acronym, it is named without the hump. For example: htmlescape,escapehtml instead of escapehtml
Key Words
Go has 25 keywords:
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 |
variables
Variable DeclarationDefine a variable with VAR declaration and its type and initial value: var name type = Expression
The type or = Expression section can be omitted, but cannot be omitted at the same time. If the type is omitted, the compiler infers the type based on expression. if = expression is omitted, the variable is initially 0 values:
-the number is initially 0
-The Boolean value is initially false
-The string is initially empty
-Interface and references are initially nil
-Arrays and structs initialize the elements or fields to a value of 0
Declare multiple variables at once:
var I, j, K int //int, int, int
var b, F, S = True, 2.3, "four" /bool Float64 string
Multiple variables are declared as return values for a function:
var f, err = OS. Open (name) //Os. Open returns a file and an error
If you declare a variable and do not use it, you will get an error. A short variable declaration can be used to declare a short variable in a function: Name: = The type of expression,name is inferred from expression. Initialize multiple variables: I, J: = 0, 1
Multiple variables are declared as function return values:
F, err: = OS. Open (name)
A multivariable declaration does not have to be a newly created variable for all variables, but at least one must be a newly created variable. Variables that have already been created in a multivariate declaration are treated as assignments:
Assume that both In,err and out are not declared
in, err: = OS. Open (infile) //OK, declare in and err
//...
Out, err: = OS. Create (outfile) //OK, declare out, assign a value to err
Suppose F,err is not declared an
F, err: = OS. Open (infile)
//...
F, err: = OS. Create (outfile) //Compile error, no new variables created
assigning values to variablesAssignment operator: = any arithmetic operator or bitwise operator followed by = The compound assignment operator is composed, for example: +=,*=
Numeric variables can use the self-increment and decrement operators to add 1 or minus 1 to their own values.
There is no pre-increment.
V: = 1
v++ //Same as V = v + 1, V becomes 2
v-- //Same as V = V-1; v becomes 1 again
Multiple Assignments
Multi-assignment allows multiple variables to be assigned at once:
I, j, K = 2, 3, 5
x, y = y, x //Exchange value of two variables
If a function or operator returns multiple values, you must use more than one variable on the left of the assignment, and the number must match the number of return values:
F, err = OS. Open ("Foo.txt") //function call return values
If you do not want to return one or more of the values with multiple functions, you can use _ instead of the following:
_, err = Io. Copy (DST, SRC)
implicitly-assigned valuesImplicit assignment occurs in the case of function parameter passing, function return value, and so on.
Pointers
The pointer stores the address of a variable. The pointer is expressed in the form of a * followed by a type, for example: *int
Use & to take the address of a variable. Use * To access the variable that the pointer refers to, for example:
X: = 0
P: = &x
*p = 1 //x now is 1
The pointer has a value of nil of 0
you can return the address of a local variable inside a function :
var p = f ()
func f () *int {
V: = 1
return &v //OK
}
new Function
The new function creates an anonymous object and returns its address, which is set to an initial value of 0:
P: = new (int) //P is *int, *p is 0
Returns the address of the local variable, equivalent to the variable created by the return new:
Func newint () *int {
return new (int)
}
//is equivalent to:
func newint () *int {
var dummy int
return &dum My
}
Empty Identity
Null identifier _, which requires a variable in syntax, but does not logically require a variable. For example, a variable that is not required in range for, the function returns a return value that is not required in the list of values.
A: = [3]string{' hello ', ' go ', ' World '} for
_, V: = range A { ///Do not need index value to _ instead of
fmt. Print (V, "")
}
_, x: = Func () (int, int) { //does not need the first return value, _ instead of return
1, 2
} ()
the visibility of variablesIf a variable is defined in a function, then it is local. If a variable is defined outside of all functions, it is visible in all files in the package. Also, if the first letter of the name is uppercase, it is visible outside the package. (The package's name is always lowercase)
the lifetime of a variableThe lifetime of a package variable (global variable) is consistent with the lifetime of the program. The lifetime of a local variable is from the beginning of life until the variable is not visible. The go language has a garbage collection mechanism, so there's no need to worry about the opening and releasing of memory. Whether a variable is created on a heap or on a stack depends on the lifetime of the variable.
If the function returns the address of a local variable, the variable is allocated on the heap. If the variable is used only locally (inside the function body, within the loop body, in the IF statement, and so on), the variable is allocated on the stack, even if it is a variable created with the new () function. Whether a function is created on a stack or on a heap is determined by the compiler without the programmer's intervention.
Word block
Scopes represent the scope of a name. The word block (lexical block) represents a range of scopes within which the scope of the name is defined. The following scopes are called Word blocks: the entire source code (also known as the Global Block), the package, the file, the function, within the FOR statement, within the IF statement, within the switch statement, in the case statement, within each pair of curly braces. The same name can be declared in different chunks, and the name in the inner word block hides the name in the outer word block, but it is a bad style.
Constants declaration of a constant
Declaring constants with const: const PI = 3.14159
Declares that multiple constants are enclosed in parentheses:
Const (
e = 2.718281
pi = 3.14159
)
Constants can be used as dimensions of an array:
Const LEN = 4
var p [len]byte
Const declares a set of constants that, in addition to the first constant, can be assigned a default value that is consistent with the previous constant:
Const (
a = 1
b //b is 1
c = 2
D //d is 2
)
constant Generator Iota
When declaring a set of constants, an expression consisting of iota can be used to assign a value to the first constant, and the expression is applied to every constant after the first constant, but the value of iota starts at 0, adds one to the next constant, and the constant that is usually assigned in this way is called an enumeration.
Const (
a = Iota //A is 0
b //b is 1
c //C are 2
D //d is 3
)
const (
flag 1 = 1 << iota //Flag1 is 1 (1 << 0)
flag2 //Flag2 is 2 (1 << 1)
flag3 //Flag 3 is 4 (1 << 2)
flag4 //FLAG4 is 8 (1 << 3)
)
No type constant
A constant without a type is an untyped constant, and an untyped constant has a greater precision than a type constant (usually up to 256 bits) and can participate in a more accurate calculation before it is given a type:
Const (
a = 1 << (+ iota)
b //b is a 100-bit integer that has exceeded the maximum UInt64 value
c //C is a 101-bit integer
)
FMT. Printf ("%d", c/b) //Print 2
Untyped constants are divided into untyped integers, non-type floating-point numbers, untyped bool values, untyped rune, and untyped complex numbers, based on the literal form of constants:
Const (
a = + //untyped integer
b = 1.0 //No type floating-point
number c = True //untyped bool value
d = ' \u1234 ' //No class Type Rune
e = 3 + 2i //No type complex number
)
Basic data Types
integer
integer Type
type |
symbols |
Number of digits |
Range |
Description |
int8 |
have symbols |
8 |
−2n−1−1∼2n−1−1-2^{n-1}-1 \sim 2^{n-1}-1 |
|
Int16 |
16 |
Int32 |
32 |
Rune |
32 |
Rune is the alias of Int32, Used to represent a Unicode code point. |
Int64 |
64 |
|
Uint8 |
No sign |
8 |
0∼2n−1 0 \sim 2^n-1 |
UInt16 |
16 |
UInt32 |
32 |
UInt64 |
64 |
Int |
have symbols |
。 |
。 |
Different compilers set different sizes based on different platforms, To achieve the most efficient use of hardware. |
UInt |
No sign |
UIntPtr |
No sign |
|
|
UIntPtr is an unsigned integral type, Used only for low-level languages (such as C). |
The integral type can be represented in addition to the 10 binary, as well as 8 binary and 16 binary. 8 before adding 0,16 before adding 0x or 0X before the system.
operator
Operators and priority levels that can be used for integral types are as follows (priority is high to low, each row has the same priority):
* |
/ |
% |
<< |
>> |
& |
&^ |
+ + |
−- |
| |
^ |
|
== |
!= |
< |
<= |
> |
>= |
|
&& |
|
|| |
|
The operators of the first two rows have a corresponding compound assignment operator, such as + + = arithmetic operator +-*/can be used for integer, floating-point, plural. The modulus operator (%) can only be used for two integers. If there is a negative number at the time of the modulo, the final symbol is determined by dividend, such as: -5%3 and -5%-3 result are-2 the result of the arithmetic operator may exceed the range of the operand's type. This triggers an overflow. Operation should be careful to choose the appropriate type of operation, so as not to overflow. comparison operator = = = < <= > >= can be applied to two types of the same base base type (integer, float, string), the result is type bool. +-can also be used as a unary operator to indicate positive or negative.
The go provides the following bitwise operators:
& |
Bitwise-AND |
| |
Bitwise OR |
^ |
XOR or |
&^ |
and non- |
<< |
Left displacement |
>> |
Right shift |
^ can also be used as a unary operator to indicate bitwise inversion. &^ is expressed with non, for example: z = x &^ y, if one of Y is 1, then the bit of Z is 0, otherwise the bit of z is the same as that of X. The right operand of << and >> must be an unsigned number. If the left-hand operand of >> is a signed number, the position is filled with the sign bit when the right shift occurs.
Print Integral type
In the use of FMT. Printf () When printing integers, 10 binary, 8 binary, 16 binary with%d%o%x (or%x for uppercase):
o: = 0123
fmt. Printf ("%d%[1]o%#[1]o\n", O) //123 0123
x: = Int64 (0xABC)
FMT. Printf ("%d%[1]x%#[1]x%#[1]x\n", x) //2748 ABC 0xabc 0XABC
# indicates the number of characters [] that are printed in the beginning of the 8 or 16 decimal indicates the number of operands to be removed from the print sequence
Print Rune type with%c (without quotation marks) or%q (quoted), print out Unicode characters:
CH: = ' in '
CH2: = ' state '
FMT. Printf ("%d%[1]c%d%[2]q\n", CH, CH2) //20013 in 22269 ' country '
floating point number
floating-point type
type |
accuracy |
Maximum Value |
Minimum Value |
Float32 |
6 guests |
Math. MaxFloat32 |
Math. MinFloat32 |
Float64 |
15 Guests |
Math. MaxFloat64 |
Math. MinFloat64 |
Print floating-point numbersPrint floating-point numbers with%f
Special Values:
Special Values |
meaning |
Example |
+inf |
Positive Infinity |
5.0/0.0 |
-inf |
Negative infinity |
-5.0/0.0 |
NaN |
Not a number |
0/0 |
Math. IsNaN tests whether a value is Nan math. Nan returns nan Nan compared to Nan to False
pluralThe go language has built-in plural types. There are two types of complex numbers: the real part and the imaginary part of the complex64 complex128,complex64 float32,complex128 are float64. Create a complex type with complex (), real () and imag () return real and imaginary parts. The literal value of the imaginary part is denoted by the number plus I. Go supports the arithmetic of complex numbers. Comparison operator Support: = = and! =
Boolean valueThe bool value of the Go language has only true and false. The following operations produce a bool value: comparison operator:> >= < <= = = =), logical non-:! Two expressions that produce a bool value can be logically associated with (&&) and logical OR (| | ) and generate short-circuit behavior (which seems to be true of all languages, at least as far as I know).
You cannot implicitly convert a numeric or pointer type to a Boolean value, and vice-versa.
stringA string is a string of byte sequences. expressed in string. Strings typically store Unicode code points (rune) in UTF8 encoding. The Len () function returns the number of bytes in a string,
the number of non-Unicode characters. Assuming that S is a string, the subscript operator S[i] Returns the value of byte I in a string,
non-I Unicode characters. Go supports string slicing: S[i:j] Returns a string starting from the first byte to the end of the J Byte (without the J byte). Any or all of the I and J can be omitted during sectioning. Omitting I is starting from 0, omitting J to the end of Len (s), and omitting the string (i.e. itself) from 0 to Len (s). String supports the + operator to stitch strings. Supports + = to stitch new strings and assign values to the variable itself. String supports comparison operators. The comparison is made in bytes. The string cannot be changed. For example, s[0]= ' V ' gets a compile error. Because the string cannot be changed, the string returned by the slice can share the same memory with the original string to improve efficiency.
string LiteralsA byte sequence enclosed in double quotation marks (") or an inverse quotation mark (') is a string literal.
A double-quote string literal with \ Start character in the backslash string does not escape character escaping characters that begin with \ 16 (starting with \x, followed by two 16 characters, such as \XAB) or 8 binary (starting with \, such as \377).
Commonly used escape characters:
character |
meaning |
\ n |
Line break |
\ r |
Enter |
\ t |
Tabs |
\’ |
Single quotation marks |
\” |
Double quotes |
\\ |
Reverse Slash |
The string that is enclosed in anti-quotes is called the original string (raw string), where the characters starting with \ are not escaped. The original string can span multiple lines, but go will automatically remove the carriage return (\ r), so that the original string remains consistent under Linux and Windows. The original string can be used in regular expressions to avoid excessive escaping. Because the Go Program source code is always saved as UTF8, and the string is also usually UTF8 parsing. Therefore, you can write any Unicode code point in string literals.
UTF-8The UTF-8 encodes Unicode in a variable length manner. The go source code is stored in UTF-8 mode. The strings in the source code are also handled in UTF-8 manner. Unicode escape: 16-bit: \uhhhh;32 bit: \uhhhhhhhh
Only a single 16-digit number less than 256 can be escaped to a rune, otherwise it can only be converted by the/U or/u mode:
var a rune = ' \x41 ' //ok
a = ' \xe4\xb8\x96 ' //error
a = ' \u4e16 ' //OK
The UTF-8 and rune related functions are provided in the Unicode/utf8 package:
Decoderuneinstring accepts a string and returns the Rune value of the first character of the string and the number of bytes required to represent this rune:
s: = "Hello"
r, Size: = UTF8. Decoderuneinstring (s)
FMT. Printf ("%q is%d bytes", R, Size)
//print: ' You ' is 3 bytes
Runecountinstring returns the number of Rune in a string
s: = "Hello"
fmt. Printf ("Rune Count:%d\nbyte count:%d",
UTF8. Runecountinstring (s), Len (s))
//print:
//Rune Count:2
//byte count:6
The range for automatically decodes the UTF-8 string as a tune sequence:
s: = "Hello"
for I, r: = range S {
fmt. Printf ("%d:%q\n", I, R)
}
//print:
//0: ' You '
//3: ' Good '
Go decoder when decoding UTF-8, if encountered illegal character sequence, then converted to \UFFFD, this character is usually a polygon in the middle of a black block. Characters: Rune and UTF-8 strings:
string to []rune will be automatically decoded to get the corresponding rune sequence. []rune to string is automatically encoded to get the corresponding UTF-8 string. The number to string converts the number first to rune and then encodes the rune to generate the corresponding string. Composite Type Array
An array is one or more
Similar type
elements are composed of
Fixed length
The sequence. expressed as [num]t, where Num is the number of elements and T is a type, for example: [3]int represents an int array with a number of 3 elements.
Declaration of the array:
var a [3]int //Create an array consisting of 3 int values
Array initialization
Initialize with array literals:
var a [3]int = [3]int{1, 2, 3}
An element that is not explicitly initialized is implicitly initialized to a value of 0:
var a [3]int = [3]int{1, 2} //a[2] is 0
var b [3]int //all elements are 0
If a. Specifies the length of the array, the true length of the array is determined by the number of elements in the initialization list:
Q: = [...] Int{1, 2, 3}//q is [3]int
The subscript can be specified when initializing:
A = [...] String{1: "He