Characteristics of Go
Simple and easy to learn: The grammar of Go is concise and clear, similar to the C language style, and is easy to learn and master.
High performance, concurrent programming: Go language natively supports concurrent programming, adopting a lightweight Goroutine concurrency model and Channel communication mechanism, making writing concurrent programs simpler and more efficient. Go language has good performance. Its compiler compiles Go code into machine code and uses a garbage collection mechanism to manage memory at runtime, effectively improving the execution efficiency of the program.
A perfect tool chain: The Go language has a rich tool set built-in, including formatting tools, testing tools, performance analysis tools, etc. Developers can easily format code, unit testing and performance. With these standard libraries, developers can build efficient, reliable and secure applications faster. In addition, the Go language community also provides a rich third-party package for developers to use and expand. Optimization and other operations.
Rich standard library: The Go language standard library is an important feature of it, it provides many feature-rich and easy-to-use packages covering a variety of fields. With these standard libraries, developers can build efficient, reliable and secure applications faster. In addition, the Go language community also provides a rich third-party package for developers to use and expand.
Cross-platform support:Go language supports a variety of mainstream operating systems and hardware architectures, and can compile and generate executable files without relying on other libraries or operating environments, making it easy to deploy and run on different platforms.
Garbage recycling: Go language automatically manages memory through a garbage collection mechanism, avoiding common memory errors, such as memory leaks and wild pointers, improving the security and stability of the program.
Static links: Go is a statically typed language. The compiler will perform type checking during the compilation stage, which can detect potential type errors in advance and reduce runtime errors.
Quick Compilation:Go language has fast compilation speed, which is due to the design and optimization of the Go compiler.
Basic syntax of Go
HelloWorld
package main //Represents a program that can be executed independently. Each Go application contains a package called main, which must contain a main packageimport ( "fmt" ) func main() { ("hello world") }
package main
Represents a program that can be executed independently, each Go application contains a name calledmain
The package must contain onemain
Bag
import
Keywords are used to import other packages (packages
) code. Import statements are usually placed at the beginning of a Go source file. Multiple packages need to be imported, placed in parentheses and separated by newlines.
fmt
It is a package in the Go language standard library that provides the function of formatting input and output. It contains a series of functions that can be used to print text, format strings, read input, etc.
Commonly usedfmt
The functions and methods are as follows:
-
: Print out the output content, no newline characters are added at the end of the text.
-
: Print out the output and add a newline at the end of the text.
-
: Format the printout content, you can use placeholders to specify the output format.
-
: Format the given parameter into a string and returns the string, no print output is performed.
-
: Format the given parameter into a string and returns the string, you can use placeholders to specify the output format.
-
: Read a value from standard input and store it in the passed variable using the specified format.
-
: Read a line of text from standard input and try to parse it into the value of the variable in the parameter list.
variable
var + variable name + variable type (in Go language, variable type is followed by variable name)
Steps to use:
1. Variable declaration
2. Assignment of variables
3. Use of variables
package main import ( "fmt" ) func main() { // Variable declarationvar A int // Assignment of variablesA = 18 // Use of variables("A = ", A) } // var can judge the variable type by yourselfvar B = 18 // Omit var with:=C := "Hello World"
Each type has a default value. If the variable is not assigned, the value of the variable is the default value.
Data Type
In Go, there are several basic data types that can be used to store different types of data. Here are the common basic data types:
-
Integer type (int): Used to represent integer values, including signed and unsigned integer types. For example:
int
、int8
、int16
、int32
、int64
、uint
、uint8
、uint16
、uint32
、uint64
wait. -
Float type (float): Used to represent decimal values, there are two types of floating point numbers with precision:
float32
andfloat64
。 -
Boolean type (bool): Used to represent logical values, with only two values:
true
andfalse
。 - String type (string): Used to represent text, enclose the text with double quotes or backquotes. For example: "Hello, Go!".
- Character Type: Used to represent a single character, enclosing characters with single quotes. For example: ‘A’.
- Pointer type: The memory address used to store variables, pointing to the memory space where the variable is located.
- Array type: A collection of elements of the same type of fixed length.
- Slice type: Used to store sequences of the same type of elements of variable length.
- Mapping type: used to store a collection of key-value pairs, similar to a dictionary.
- Structure type: Used to define custom composite data types, which can contain different types of fields.
Pointer type
//statementvar Pointer variable name *Data Type //AssignmentPointer variable name = & Variable name //Change the variable value through pointer*Pointer variable name = New value
Pointer variable name
It's the name you gave to the pointer variable
Data Type
is the data type of the variable pointed to by the pointer. The preceding pointer variable name*
Indicates that the variable is a pointer variable.
Pointers are commonly used in the following situations in Go language:
- Pass large data structures to avoid performance losses caused by copying the entire data structure;
- Modify the value of the actual parameter through pointers;
- Dynamically allocate memory.
It should be noted that before using the pointer, you need to make sure that the pointer is notnil
(Null pointer), otherwise a runtime error will be raised.
Branch structure (if statement, switch statement)
- Single branch
if
if Conditional expression { Logical code }
- Double branch
if-else
if Conditional expression { Logical code } else{ Logical code }
- Multiple branches
_if
if Conditional expression { Logical code } else if Conditional expression { Logical code } ...... else{ Logical code }
-
switch
Statement
switch expression { case value1,value2, ...: Statement block1 case value1,value2, ...: Statement block2 .... default: }
Loop structure for loop
- Basic for loop: Initialize a counter before the loop starts, and then update the counter after each loop iteration until the counter reaches a predetermined value.
for initialization; condition; renew { // The code block that loops out}
For example, the following code prints integers from 0 to 4:
for i := 0; i < 5; i++ { (i) }
- Omit initialization and update: If initialization and update steps are not required, they can be omitted.
for condition { // The code block that loops out}
For example, the following code will keep printing the current number of seconds until it reaches 10 seconds:
for ().Second() < 10 { (().Second()) }
-
Infinite loop: If the condition part is omitted, the code block will be executed infinitely unless it is used
break
orreturn
The statement terminates the loop.
for { // The code block that loops out}
for range
In Go,for range
It's a specialfor
Loop form, used to traverse data structures such as arrays, slices, strings, maps and channels.
for range
The syntax of is as follows:
for index, value := range expression { // The code block that loops out}
in,
-
index
is the index or key of the current element. -
value
is the value of the current element, -
expression
It is the data structure to iterate.
usefor range
Loops can easily get the index and value of each element, which is suitable for traversing the entire data structure. In each iteration,index
andvalue
It will be reassigned to the index and value of the next element until the complete data structure is traversed.
Here are some examples:
Iterate over an array or slice:
numbers := []int{1, 2, 3, 4, 5} for index, value := range numbers { (index, value) }
This example outputs the index and value of each element in the array/slice.
Traversing the string:
text := "Hello, Go!" for index, value := range text { (index, value) }
This example outputs the index of each character in the string and the corresponding Unicode code point value.
Traversal mapping:
person := map[string]interface{}{ "name": "Alice", "age": 25, "gender": "female", } for key, value := range person { (key, value) }
This example outputs the keys and values for each key-value pair in the map.
Traversal channel:
data := make(chan int) go func() { data <- 1 data <- 2 close(data) }() for value := range data { (value) }
This example receives values from the channel in turn and prints them out.
It should be noted that for strings and maps,index
It is actually the byte index of the key or key of each element.
for range
Running is used very widely, especially when it is necessary to iterate over data structures.
function
Improve code reusability and maintenance and reduce code redundancy
//Declaration of function func Function name (List of formal parameters)(Return value type list){ Execution statement return + Return to the value list } //Call of functionFunction name + (Formal parameters1,Formal parameters2,...)
Notice
Function name: capital letter, can be accessed in this package file and other package files (similar to public)
Function name: The first letter is lowercase, and can only be accessed by this package file (similar to private)
Go language functions can have multiple return values
Go language function is a data type assigned to a variable, and can also be treated as a formal parameter and return.
Functions in GoReloading is not supported,butSupports variable parameters
package main // Define a function with the function parameters as: Variable parameter name + ... + Parameter typefunc test (num...int){ //The function handles variable parameters as slices} func main(){ test() test(1) test(2,28,30) test(2,...,100) }
The above is the detailed content of the basic grammar and common feature analysis of Go language introduction. For more information about Go grammar and features, please pay attention to my other related articles!