Go basis

This article has participated in the weekend learning program, click the link to see more details: juejin.cn/post/696572…

Go Environment Installation (Windows)

Installation address: golang.google.cn/dl/

A foolproof installation that should automatically configure environment variables after installation

After the installation, check whether environment variables are configured successfully. If the environment variables are not configured successfully, manually configure them

Go version / / incmdThe current GO version is displayed when you enter this commandCopy the code
hello world

Go editor goland or vscode

package main    // define package main as the main program of the package

import "fmt"    // Import go standard library FMT

func main(a) {
   fmt.Println("Hello, World!")}go run <filename>.go  // Run the program command using goland configurable start configuration click start
Copy the code

Language structure of go

  • Package declaration package
  • Introducing the package import
  • Function func main ()
  • variable
  • Statement & expression
  • annotation

The go keyword

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

Go data type

  • Boolean (true or false)
    var b bool = true
    Copy the code
  • Number type (integer int float32 float64)
    • plastic
    The serial number Type and Description
    1 uint8Unsigned 8-bit integer (0 to 255)
    2 uint16Unsigned 16-bit integer (0 to 65535)
    3 uint32Unsigned 32-bit integer (0 to 4294967295)
    4 uint64Unsigned 64-bit integer (0 to 18446744073709551615)
    5 int8Signed 8-bit integers (-128 to 127)
    6 int16Signed 16-bit integers (-32768 to 32767)
    7 int32Signed 32-bit integers (-2147483648 to 2147483647)
    8 int64Signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
    • floating-point
    The serial number Type and Description
    1 float32Ieee-754 32-bit floating point number
    2 float64Ieee-754 64-bit floating point number
    3 complex6432-bit real and imaginary numbers
    4 complex12864-bit real and imaginary numbers
    • Other numeric types
    The serial number Type and Description
    1 byteSimilar uint8
    2 runeSimilar int32
    3 uint32 or 64 bits
    4 intSame size as uint
    5 uintptrAn unsigned integer used to hold a pointer
  • String type

  • The derived type

    • Pointer type
    • An array type
    • Structure (struct)
    • Channel
    • function
    • switch
    • Interface
    • Map

Go language variable

The rule for defining variable names consists of letters, digits, and underscores (_). The first letter cannot be a number

A variable defined in GO must be used, or it will compile an error

In the import package or accept the return value of the function, if you do not want to use it, you can use _ receive to indicate that the value is discarded

Var a, b int var a string = '123' var a, b int = 1, Var a = 1 var b = true var a = 1 var b = true Func main() {a := 1} func main() {a := 1} // a := 1 // is equal to var a int Var (a int b string)Copy the code

Zero value

*int []int map[string] int chan int func(string) int error // Error is the interfaceCopy the code

Value type and reference type

  • The value type (int float bool string) is stored on the stack (much like JS)

  • Reference types

    A reference type stores a memory address (pointer) through which data is accessed

    Pointers to the same reference type can be contiguous or scattered in memory

    R2 = R1 assignment between reference types, only reference addresses are assigned

Go constants

Const a int = 1 const b string = "123" const (Man = 0 woMan = 1)Copy the code
Iota special constants Constants that can be modified by the compiler
Const (a = iota b c) const (a = iota b c) const (a = iota b c)Copy the code

The instance

Package main import "FMT" func main() {const (a = iota //0 b //1 c //2 d = "ha", Iota +=1 e //"ha" iota +=1 f = 100 g //100 ioTA +=1 h = ioTA //7, recovery count I //8) fmt.Println(a,b,c,d,e,f,g,h,i) }Copy the code

The operator

  • Arithmetic operator
  • Relational operator
  • Logical operator
  • An operator
  • The assignment operator
  • Other operators
  1. Arithmetic operator
The operator describe
+ add
Subtracting the
* multiply
/ division
% For more than
++ Since the increase
Since the reduction of

2. Relational operators

The operator describe
= = Checks if two values are equal, returning True if they are, False otherwise.
! = Checks if two values are not equal, returning True if not False otherwise.
> Checks if the value on the left is greater than the value on the right, and returns True if so, False otherwise.
< Checks if the value on the left is less than the value on the right, and returns True if so, False otherwise.
> = Checks if the value on the left is greater than or equal to the value on the right, and returns True if so, False otherwise.
< = Checks if the value on the left is less than or equal to the value on the right, and returns True if it is False otherwise.

3. Logical operators

The operator describe
&& The logical AND operator. Condition True if both operands are True, False otherwise.
|| The logical OR operator. Condition True if both operands have a True, otherwise False.
! Logical NOT operator. If the condition is True, the logic NOT condition False, otherwise True.
  1. Bit operation (no, can’t understand)

  2. The assignment operator

    The operator describe
    = A simple assignment operator that assigns the value of an expression to an lvalue
    + = Add them and assign them
    – = Subtract and assign
    * = Multiply and assign
    / = Divide and assign
    % = Remainder and then assign
    < < = Assign after left shift
    > > = Assign after right shift
    & = Assignment by bit and post
    ^ = Xor post assignment by bit
    | = Assignment by bit or post

6. Other operators

The operator describe The instance
& Returns the variable storage address &a; The actual address of the variable is given.
* Pointer variables. *a; Is a pointer variable
Operator priority
priority The operator
5 * / % << >> & &^
4 + – | ^
3 = =! = < <= > >=
2 &&
1 ||

Go conditional statement

  • if

    var a int  = 10
    if a < 20 {
    	
    }
    Copy the code
  • if else

    var a int  = 10
    if a < 8 {
    	
    } else {
    	
    }
    Copy the code
  • switch

    Switch does not need to add a break match to automatically stop

    Fallthrough can be used if the match needs to be executed

    A switch can match multiple values in a case

    Var a int = 50 switch a {case 90: case 80: case 50,60,70: default:}Copy the code

    Type switch

    var x interface {}
    switch i := x.(type) {
    	case int: 
    	case nil:
    	case float64:
    	default
    }
    Copy the code

    fallthrough

    Using fallthrough enforces subsequent case statements. Fallthrough does not determine whether the expression in the next case is true.

    Func main() {switch {case false: FMT.Println("1, case conditional statement false") fallthrough case true: Println("2, case conditional statement true") fallthrough case false: FMT.Println("3, case conditional statement false") fallthrough case true: Println("4, case conditional statement true") case false: FMT.Println("5, case conditional statement false") fallThrough default: Println("6, default case")}}Copy the code
  • select

    Select is a control structure in Go, similar to the switch statement used for communication. Each case must be a communication operation, either send or receive.

    Select randomly executes a runnable case. If there are no cases to run, it blocks until there are cases to run. A default clause should always run.

    var c1, c2 chan int
    var i1, i2 int
    
    select {
      case i1 = <-c1:
      	fmt.Printf(i1)
      case c2 <- i2:
      	fmt.Printf(c2)
      default: 
      	fmt.Printf('')
    }
    Copy the code

Go cycle

  • Common for
func main() { sum := 0 for(i := 0; i<= 10; Sum () {sum := 1 for; sum := 1 for; Sum <= 10 {sum += sum}} func main() {sum := 1 for sum <= 10 {sum += sum}} func main() { sum := 1 for { sum += sum } }Copy the code
  • For range can slice an array of strings and so on

    Func main() {strings := []string{"vue", "react"} for I,v := range strings {FMT.Printf(I,v) // I is index v is value}}Copy the code

    Go loop control statement

  • Break Interrupts the for loop or switch

  • Continue Jumps out of this loop for the next loop

  • Goto transfers control to the marked statement

Go function

Function defined form

Func function_name([parameter list]) [return_types] {body} func Max (num1, num2 int) (int, int) {return num1, num2} func function_name([parameter list]) [return_types] {body} func Max (num1, num2 int) (int, int) {return num1, num2}Copy the code
Function and the cords
  • Value passing calls the function to copy arguments into the function
  • Passing by reference passes the address of a parameter to a function, changing the parameter to affect the actual parameter
Func Max (num1, num2 int) (int, int) {return num1, num2} func main() {Max (1, 2)} y *int) { var a int a = *x *x = *y *y = a } func main() { var a int = 100 var b int = 200 max(a,b) }Copy the code

Go way

Go has both functions and methods. A method is a function that contains a acceptor, which can be a value of a named or struct type or a pointer. All methods of a given type belong to the set of methods of that type.

Define method structure

Func (variable_name variable_data_type) function_name() [return_type]{/* Function body */}Copy the code
Package main import (" FMT ") /* Define struct */ type Circle struct {radius float64} func main() {var c1 Circle c1.radius = 10.00 FMT.Println(" Circle area = ", C1.getarea ())} func (c Circle) getArea() float64 {// c.adius is a property of Circle 3.14 * c.adius * c.adius}Copy the code

An array of

Declare array Array length is fixed

Var arrayList [10]int{1,2,3,4} arrList := [...] Int {} // use... ArrList := [5]int{1:100, // The number of elements in {} cannot exceed the specified length */ / Access array elements by subscript access arrList[0]Copy the code