Go language quick start

Posted by The Merg on Thu, 20 Jan 2022 02:32:42 +0100

Go language quick start learning

Go is an open source programming language that makes it easy to construct simple, reliable and efficient software. And in today's Internet companies, go is more and more widely used.

The following are my personal notes according to my own introduction plan, and I will refer to rookie programming and Go language Bible Chinese version website as a quick start. If there are any mistakes in the following contents or your understanding is not in place, please criticize and correct the onlookers. Thank you very much.

Here are my two learning websites:

Introduction to rookie programming go language: Official website

Go language Bible Chinese version: Go language Bible

1. Introduction to Go language

1.1 development and characteristics of go language

When it comes to Go language, one thing to think of is that Ken Thomson will appear in the invention of C language and Go language. The C language was invented to solve the problem of UNIX system portability, while the legendary team also invented the Go language in order to solve the increasingly complex programming problems in the multi-core and networked environment of the 21st century.

Go language was designed and implemented by Daniel from Google in 2007 and officially released in November 2009. It has a grammatical appearance similar to that of C language, and uses many other good places for reference. Its characteristics are summarized as follows:

  • Simple, fast and safe
  • Parallel, interesting, open source
  • Support data abstraction and object-oriented programming
  • Integrated GC garbage collection
  • Memory management, fast compilation
  • The most popular alternative to typeless scripting languages

1.2 Go installation

Combined with the operation of your computer, here is a brief introduction to the installation under windows

  1. Use address: https://golang.google.cn/dl/
  2. Download the msi suffix. After downloading, you can find the file in the browser list.
  3. Change the download address according to your needs and click Install.
  4. Configure the environment. After selecting my own installation directory and opening the environment configuration, I found that it has automatically configured the bin directory under go in the system directory. Open cmd and enter > go can also be displayed normally.

1.3 structure of go language

In rookie programming, the following structures are described:

  • Package declaration
  • Import package
  • function
  • variable
  • Statement & expression
  • notes

1.4 first procedure

1. First write the following code

package main  //Define package name
import "fmt"  //Tell the compiler that the program uses fmt packages (functions or other elements)
func main(){ //Start of program
    fmt.Println("hello world!")
}

2. Compile run & run results

C:\Users\86188\Desktop>go run hello.go
Hello world!

2. Introduction to Go language

Firstly, for computer architecture, memory, arithmetic unit, controller and input and output equipment are all important structures. Here, the program should first obtain external input, that is, let the computer obtain the input source through user input, file, output of other programs, etc.

2.1 escape characters

  • \t: Represents a tab, usually used for roster alignment.
  • \n: Newline character
  • \: one\
  • : one
  • \r: A carriage return

2.2 notes

  • Line comments: / / basic content
  • Block comment: / * basic content*/

The Go language recommends using line annotations to annotate the entire method and statement.

2.3 Go language coding style

1. The first is the placement of braces

//error
func main() 
{
	fmt.Print("hello,world!") //shirt+alt + up and down arrows -- > copy up and down
}
//correct
func main() {
	fmt.Print("hello,world!") //shirt+alt + up and down arrows -- > copy up and down
}

2. The next is the characters struck in one line, which can not exceed 80 characters. And if it exceeds, it is necessary to use newline display to maintain the elegance of the format.

2.4 subsequent language standard library

Many go languages can be found and used from the go language standard library. You can click the following website:

https://studygolang.com/pkgdoc

3. Go variable

Variable is the representation of data storage space in memory. For us, we don't need to care about its physical storage, but we need to be able to use it flexibly.

Of course, variables are divided into declaration, non variable assignment and use variables.

For example, I can enter the following:

var i int
i = 10
fmt.Print(i)

At this time, there should be variable storage about i in memory, which should be equivalent to learning the method area in the Java virtual machine, that is, storing variables and other information. This storage contains both values and types.

Assignment method of variable

  • Specifies the variable type. After declaration, the default value is adopted without assignment
  • Determine the type of the variable according to the value
  • Copy with: = if: = left variable name is not used

One time multi declaration variable

var n1 = 100
	var n2 = 200
	var name = "jack"
	var (
		n3    = 300
		n4    = 400
		name1 = "matt"
	)
	fmt.Print("Character is:", n1, n2, n3, n4, " ", name, " ", name1)

The output is as follows: characters: 100 200 300 400 jack matt

Variable conversion

Variables in the same scope cannot have the same name. For example, if you encounter a place that needs type conversion, you are likely to report an error.

Addition, subtraction, multiplication and division, as the symbol of operation, are omitted here, but the general type conversion is mainly based on the current type. For example, int+int=int.

4. Introduction to data types

Data types include basic data types and derived complex data types.

4.1 int type

int signed type

Int types are divided into int8\int16\int32\int64 in go language. The difference here is how many bits are used to represent an int type value.

typeSign or notOccupied storage spaceScope of expressionother
int8have1 byte-27~27-1
int16have2 bytes-215~215-1
int32have4 bytes-231~231-1
int64have8 bytes-263~263-1

In other words, when programming, we need to pay attention to selecting the type according to the size of our assignment content, otherwise the use of too small type can not express the content you need to assign, and there will be compilation errors.

int unsigned type

typeSign or notOccupied storage spaceScope of expressionother
uint8nothing1 byte0~2^8-1
uint16nothing2 bytes0~2^16-1
uint32nothing4 bytes0~2^32-1
uint64nothing8 bytes0~2^64-1

Of course, if it is a 32-bit computer, it should be the corresponding 4-byte part; If it is 64 bits, it should be the corresponding 8-byte part.

In the integer variables of Go language program, we try to use a small space to store some variables with certain meaning. For example, we take byte to represent a person's age.

4.2 float type

Float is divided into single precision and double precision. Of course, it corresponds to both float32 and float64.

As for floating point numbers, it should be enough to master their use. For example:

var num float32=-0.00089 //Sign bit plus exponent bit plus trailing digit

When selecting types, we should note that if a program needs to maintain its data accuracy, it can use 64 bits.

Method of representing floating point numbers (scientific counting):

num := 5.012345e6
num1 := 5.012345e6
num2 := 5.012345e-2
fmt.Print("The result is:", num, num1, num2)

The result is:

The result is:5.012345e+06 5.012345e+06 0.05012345

4.3 character type

Store a single character -- byte representation

Store a string of fixed length characters - character type

When using character types, you should pay attention to the use of some escape characters. For example, using \ n for line feed indicates that the path needs to be entered: \ \ to represent a \.

Go language uses utf8 coding, so you can refer to the utf8 coding table.

4.4 boolean type

Boolean types, also known as bool types, allow only True and False values.

bool type occupies one byte, which is suitable for logical operation.

4.5 String type

A string is a character sequence connected by a string of fixed length characters. Similarly, the string bytes of Go language use utf8 encoding to identify Unicode.

In this way, in fact, if we use utf8 coding format, the problem of Chinese garbled code can be solved.

var str = "hello"
str[0] = 'H'
fmt.Printf(str)

The operation is as follows:

src\go_code\LearningHello\main\hello.go:7:9: cannot assign to str[0] (strings are immutable)

It means that its content cannot be changed, and the string is immutable.

String indicates:

  • Double quotation mark
  • backquote

Splice characters:+

4.6 data type conversion

In go language, data type conversion is from small to large, or from large to small. What is converted is the data stored in the variable, and the data type of the variable itself has not changed.

func main() {
	var i int32 = 100
	var n1 float32 = float32(i)
	var n2 int8 = int8(i)
	var n3 int64 = int64(i)
	fmt.Printf("i=%v n1=%v n2=%v n3=%v \n", i, n1, n2, n3)
	fmt.Printf("i type is %T\n", i)
}
[Running] go run "d:\GoWorkplace\src\go_code\LearningHello\main\hello.go"
i=100 n1=100 n2=100 n3=100 
i type is int32

4.7 conversion of basic data type and string type

Method 1: use sprint function (more convenient)

var num1 int = 100
var str string
str = fmt.Sprintf("%d", num1)
fmt.Printf("str type %T str=%q\n", str, str)
//result
str type string str="100"

Method 2: use strconv package function

4.8 pointer

The basic data type is that variables store values, also known as value types.

Among them, to obtain the address of the variable, use &.

The pointer type is an address type. Because we said that a variable storage includes variable type and variable content, that is, we assign a value to the pointer type is to point to the address of the variable we need to point to. Only when we point to the address can it be called a pointer.

For example:

var ptr *int = &num
//Note that type mismatches are not considered here. If there is a type mismatch, an error will occur.

4.9 reference type

The reference type is that the variable stores an address, and the space corresponding to this address is the real storage data. Memory is usually allocated on the heap. At this time, if no variable references this address, the data space corresponding to this address will become garbage and will be recycled by GC.

5. Language operator

The built-in operators of Go language are:

  • Arithmetic operator
  • Relational operator
  • Logical operator
  • Bitwise Operators
  • Assignment Operators
  • Other Operators

5.1 arithmetic operators

operatordescribeexample
+AddA + B output result 30
-subtract A - B output result - 10
*MultiplyA * B output result 200
/be divided byB / A output result 2
%Seeking remainderB% a output result 0
++Self increasingA + + output result 11
Self subtractionA -- output result 9

5.2 relational operators

operatordescribeexample
==Check whether the two values are equal. If they are equal, return True; otherwise, return False.(A == B) is False
!=Check whether the two values are not equal. If not, return True; otherwise, return False.(a! = b) is True
>Check whether the left value is greater than the right value. If yes, return True; otherwise, return False.(a > b) is False
<Check whether the left value is less than the right value. If yes, return True; otherwise, return False.(a < b) is True
>=Check whether the left value is greater than or equal to the right value. If yes, return True; otherwise, return False.(a > = b) is False
<=Check whether the left value is less than or equal to the right value. If yes, return True; otherwise, return False.(a < = b) is True

5.3 logical operators

operatordescribeexample
&&Logical AND operator. If both operands are True, the condition is True; otherwise, it is False.(A & & B) is False
||Logical OR operator. If there is a True operand on both sides, the condition is True; otherwise, it is False.(a | b) is True
!Logical NOT operator. If the condition is True, the logical NOT condition is False, otherwise it is True.! (A & & B) is True

5.4 bit operators

pqp & qp | qp ^ q
00000
01011
11110
10011

5.5 assignment operators

operatordescribeexample
=A simple assignment operator assigns the value of an expression to an lvalueC = A + B assigns the result of the A + B expression to C
+=Add and assignC += A equals C = C + A
-=Subtraction before assignmentC -= A equals C = C - A
*=Multiply and assignC *= A equals C = C * A
/=Divide and assignC /= A equals C = C / A
%=Assign value after remainderC% = a equals C = C% a
<<=Left shift assignmentC < < 2 equals C = C < < 2
>>=Assignment after shift rightC > > = 2 equals C = C > > 2
&=Bitwise and post assignmentC & = 2 equals C = C & 2
^=Assignment after bitwise XORC ^= 2 equals C = C ^ 2
|=Bitwise or post assignmentC | 2 equals C = C | 2

5.6 other operators

operatordescribeexample
&Return variable storage address&a; The actual address of the variable will be given.
*Pointer variable.*a; Is a pointer variable

5.7 operator priority

Some operators have higher priority, and the operation direction of binary operators is from left to right. The following table lists all operators and their priorities. From top to bottom, the priority is from high to low:

priorityoperator
5* / % << >> & &^
4+ - | ^
3== != < <= > >=
2&&
1||

6. Go language loop conditional statement

6.1 cycle

Circular statement

The Go language provides the following types of circular processing statements:

Cycle typedescribe
for loopRepeat statement block
loop nesting Nest one or more for loops within a for loop

Loop control statement

Loop control statements can control the execution of statements in a loop.

GO language supports the following loop control statements:

Control statementdescribe
break statementIt is often used to break the current for loop or jump out of the switch statement
continue statementSkip the remaining statements of the current loop and proceed to the next loop.
goto statementTransfers control to the marked statement.
for i := 0; i < 10; i++ {
	fmt.Println("I love learning Go language")
}
/*result:
I love learning Go language
 I love learning Go language
 I love learning Go language
 I love learning Go language
 I love learning Go language
 I love learning Go language
 I love learning Go language
 I love learning Go language
 I love learning Go language
 I love learning Go language
*/

6.2 conditional statements

Go language provides the following conditional judgment statements:

sentencedescribe
if statementAn if statement consists of a Boolean expression followed by one or more statements.
if... else statementAn optional else statement can be used after the if statement. The expression in the else statement is executed when the Boolean expression is false.
if nested statementYou can embed one or more if or else if statements in an if or else if statement.
switch statementswitch statements are used to perform different actions based on different conditions.
select statementThe select statement is similar to the switch statement, but select randomly executes a runnable case. If there is no case to run, it will block until there is a case to run.

There is no need to put parentheses when using go language to judge if.

7. Functions & packages

7.1 function syntax

func Function name(parameter list )(Return value list){
    Execute statement...
    return Return value list
}
/* The function returns the maximum value of two numbers */
func max(num1, num2 int) int {
	/* Define local variables */
	var result int

	if num1 > num2 {
		result = num1
	} else {
		result = num2
	}
	return result
}

7.2 introduction package

  • import method 1: import "package name"
  • Import method 2: import("package name" or "package name")

be careful:

During import, the path is searched from src under $GOPATH, and the working directory without src is automatically imported from under src.

Then, the files of other packages can access the internal functions of this package. At this time, we need to capitalize the function name. This is equivalent to adding public.

When accessing other functions or variables, the syntax is: package name Function name

A package cannot have the same function name

7.3 recursion

Function recursion should follow the following principles:

  • When a function is executed, a new protected independent space is created

  • The local variables of a function are independent and do not affect each other

  • Recursion must approach the condition of exiting recursion, otherwise it will enter infinite recursion.

  • When a function is executed or encounters a return, it will be returned to whoever calls it. Of course, calling return means that the function itself is destroyed by the system.

8. Array

Array creation

The Go language provides many array type data structures. First, let's declare an array:

//Here, an array arr with length of 10 and type of 32 is defined
var arr [10] float32

Initialize array:

//Two ways to declare an array
var arr = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
arr :=[5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}

As you can see, in fact, we only need to care about the initialization format difference to the left of the equal sign.

In addition, if you are not sure about the array length, you can use To replace:

var arr = [...]float32{1000.0, 2.0, 3.4, 7.0, 50.0}

In this way, the sub compiler will infer the length of the array according to the number of elements.

Use of arrays

Format: array name [subscript]. For example, arr[2] uses an arr array to access the third element.

Array traversal

Here we focus on the traversal of arrays. We can use the following syntax to help us traverse:

for index,value:=range array{
...
}
  • index: subscript. If you don't want to flag, the subscript can be used_ express.
  • value: the subscript element.
  • Both are local variables.
  • range is the keyword, and array is the array traversed by the target.

9. Structure

In my opinion, structure is a very useful knowledge point of object-oriented design. The structure format of Go language is as follows:

type struct_variable_type struct {
   member definition
   member definition
   ...
   member definition
}

The first is to fill in the type keyword, then define a structure type, and then fill in struct.

For example:

type Class struct{
	students int
	teacher int
}

The second is to access the structure:

var Class1 Class
Class1.student=52
Class1.teacher=8

Structures can also be used as parameters, which is easy to understand. Next, the structure can be used as a pointer for a little understanding.

package main

import "fmt"

type Books struct {
	title   string
	author  string
	subject string
	book_id int
}

func main() {
	var Book1 Books /* Declare Book1 as a Books type */
	var Book2 Books /* Declare Book2 as a Books type */

	/* book 1 describe */
	Book1.title = "Go language"
	Book1.author = "www.runoob.com"
	Book1.subject = "Go Language course"
	Book1.book_id = 6495407

	/* book 2 describe */
	Book2.title = "Python course"
	Book2.author = "www.runoob.com"
	Book2.subject = "Python Language course"
	Book2.book_id = 6495700

	/* Print Book1 information */
	printBook(&Book1)

	/* Print Book2 information */
	printBook(&Book2)
}
func printBook(book *Books) {
	fmt.Printf("Book title : %s\n", book.title)
	fmt.Printf("Book author : %s\n", book.author)
	fmt.Printf("Book subject : %s\n", book.subject)
	fmt.Printf("Book book_id : %d\n", book.book_id)
}

The meaning here is that the memory space has allocated two spaces of Book1 and Book2 for value storage. After storing the value, point to its address through the pointer, that is, the accessed data type and parameters.

10. Slice

Enter a simple procedure first:

func main() {
	var intArr [6]int = [...]int{1, 22, 33, 44, 55, 66}
	slice := intArr[0:4]
	fmt.Println("intArr=", intArr)
	fmt.Println("slice The element is =", slice)
	fmt.Println("slice Number of elements =", len(slice))
	fmt.Println("slice The element capacity is =", cap(slice))
}

The result output is as follows:

intArr= [1 22 33 44 55 66]
slice The element is = [1 22 33 44]
slice Number of elements = 4
slice The element capacity is = 5

First, the slice should be left open and right closed, that is, the subscript value can be obtained on the left and not on the right.

The second is the number, which is also output according to the number of slices.

The capacity can be dynamically transformed here, which is the same as the length of the array.

The bottom implementation is also a structure.

type slice struct{
	ptr *[2]int
	len int
	cap int
}

The general process is that it points to the starting position of the slice, and intercepts the data of the array according to the len length and cap. That is, slice is a reference type, and the underlying implementation uses a structure.

Sorting and application:

package main

import "fmt"

func main() {
	var num []int
	printSlice(num)

	/* Allow appending empty slices */
	num = append(num, 0)
	printSlice(num)

	/* Add an element to the slice */
	num = append(num, 1)
	printSlice(num)

	/* Add multiple elements at the same time */
	num = append(num, 2, 3, 4)
	printSlice(num)

	/* Creating slice numbers1 is twice the capacity of the previous slice*/
	num1 := make([]int, len(num), (cap(num))*2)

	/* Copy the contents of numbers to numbers1 */
	copy(num1, num)
	printSlice(num1)
}

func printSlice(x []int) {
	fmt.Printf("len=%d cap=%d slice=%v\n", len(x), cap(x), x)
}

/*
The results are as follows:
len=0 cap=0 slice=[]
len=1 cap=1 slice=[0]
len=2 cap=2 slice=[0 1]
len=5 cap=6 slice=[0 1 2 3 4]
len=5 cap=12 slice=[0 1 2 3 4]
*/

11. map set

A Map is an unordered collection of key value pairs. The most important point of Map is to quickly retrieve data through key. Key is similar to index and points to the value of data.

Define map

/* Declare variables. The default map is nil */
var map_variable map[key_data_type]value_data_type
/* Using the make function */
map_variable := make(map[key_data_type]value_data_type)

Use map

	var countryCapitalMap map[string]string /*Create collection */
	countryCapitalMap = make(map[string]string)

	/* map Insert the key - value pair and the corresponding capital of each country */
	countryCapitalMap["France"] = "Paris"
	countryCapitalMap["Italy"] = "Rome"
	countryCapitalMap["Japan"] = "Tokyo"
	countryCapitalMap["India "] = "New Delhi"

	/*Use the key to output map values */
	for country := range countryCapitalMap {
		fmt.Println(country, "The capital is", countryCapitalMap[country])
	}

	/*See if the element exists in the collection */
	capital, ok := countryCapitalMap["American"] /*If it is determined to be true, it exists, otherwise it does not exist */
	/*fmt.Println(capital) */
	/*fmt.Println(ok) */
	if ok {
		fmt.Println("American Our capital is", capital)
	} else {
		fmt.Println("American Your capital does not exist")
	}

Integrate the creation of key value pairs, assign values, and judge whether the key value pairs exist. The results run as follows:

France The capital is Paris
Italy The capital is Rome
Japan The capital is Tokyo
India  The capital is New Delhi
American Your capital does not exist

Delete key value pairs:

/* Create map */
        countryCapitalMap := map[string]string{"France": "Paris", "Italy": "Rome", "Japan": "Tokyo", "India": "New delhi"}

        fmt.Println("Original map")

        /* Print map */
        for country := range countryCapitalMap {
                fmt.Println(country, "The capital is", countryCapitalMap [ country ])
        }

        /*Delete element*/ delete(countryCapitalMap, "France")
        fmt.Println("French entry deleted")

        fmt.Println("Map after deleting elements")

        /*Print map*/
        for country := range countryCapitalMap {
                fmt.Println(country, "The capital is", countryCapitalMap [ country ])
        }

Results after deletion:

Original map
India The capital is New delhi
France The capital is Paris
Italy The capital is Rome
Japan The capital is Tokyo
 French entry deleted
 Map after deleting elements
Italy The capital is Rome
Japan The capital is Tokyo
India The capital is New delhi

12. Go language interface

Go interface format

The Go interface has roughly the same usage as the Java language interface. The format is as follows:

/* Define interface */
type interface_name interface {
   method_name1 [return_type]
   method_name2 [return_type]
   method_name3 [return_type]
   ...
   method_namen [return_type]
}

/* Define structure */
type struct_name struct {
   /* variables */
}

/* Implementation interface method */
func (struct_name_variable struct_name) method_name1() [return_type] {
   /* Method implementation */
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
   /* Method implementation*/
}

Examples are as follows:

package main

import (
    "fmt"
)

type Phone interface {
    call()
}

type NokiaPhone struct {
}

func (nokiaPhone NokiaPhone) call() {
    fmt.Println("I am Nokia, I can call you!")
}

type IPhone struct {
}

func (iPhone IPhone) call() {
    fmt.Println("I am iPhone, I can call you!")
}

func main() {
    var phone Phone

    phone = new(NokiaPhone)
    phone.call()

    phone = new(IPhone)
    phone.call()

}

/*
The results are as follows:
I am Nokia, I can call you!
I am iPhone, I can call you!
*/

13. Go error handling

Go format

type error interface {
	Error() string
}
func Sqrt(f float64) (float64, error) {
    if f < 0 {
        return 0, errors.New("math: square root of negative number")
    }
    // realization
}

Topics: Go Back-end