当前位置:网站首页>[go basics] 2 - go basic sentences

[go basics] 2 - go basic sentences

2022-07-04 07:43:00 Li Yian QSR

One 、Go The data type of the language

 Insert picture description here

Data types cannot be implicitly converted at all
Such as :
var a int32 = 1
var b int64 = 2
a = b

  • Pointer types
    • Pointer operation not supported
    • string Value type , Its default initialization value is an empty string , No nil
package main

import "testing"

func TestOne(t *testing.T)  {
    
   // The pointer 
   a := 1
   aPtr := &a
   t.Log(a,aPtr)
   t.Logf("%T %T",a,aPtr)

   // Pointer operation is not allowed for pointer 
   //aPtr += 1

   var s string // The default initialization is  “”, No nil
   t.Log("*" + s + "*")
}

Two 、 Operator

 Insert picture description here
 Insert picture description here
 Insert picture description here
 Insert picture description here
 Insert picture description here

3、 ... and 、 Cycles and conditions

1、 loop

go Only support for

package class01

import "testing"

//for A circular explanation 
/* go Language only supports for loop  */

// How to write a finite loop 
func TestOne5_1(t *testing.T) {
    
   n := 0
   for n < 5 {
    
      n++
      t.Log(n)
   }
}

// How to write an infinite loop 
func TestOne5_2(t *testing.T) {
    
   n := 0
   for {
    
      t.Log(n)
   }
   // how break Well ?
   //for {
    
   // t.Log(n)
   // if n == 10 {
    
   // break
   // }
   // n++
   //}
}

2、if

 Insert picture description here
 Insert picture description here

package class01

import "testing"

// How to write a condition 
func TestOne6_1(t *testing.T) {
    
   n := 0
   if n == 1 {
    
      t.Log("n Input 1")
   } else if n == 0 {
    
      t.Log("n Input 0")
   } else {
    
      t.Log("n I don't know what I entered ")
   }

   // What is different from other languages is   The condition must be bool type , Integer or character type is not allowed , Because there is no implicit conversion 
   /* if 1 { } */
}
  • case By default, there is break, therefore go There is no need to
  • case You can add more at the back case, Anyone who hits can enter
package class01

import "testing"

func TestOne7_1(t *testing.T) {
    
   n := 0
   switch n {
    
   // The second way 
   //switch n := 0 n {
    
   case 0, 1:
      t.Log("memexixi")
   case 2, 3, 4:
      t.Log("halouhalou")
   default:
      t.Log("*********")
   }
}

/* summary : 1、switch Can be followed by an assignment expression , Such as functions, etc , Another variable to judge  2、 The default for each case There are... In the back break, There is no need to add... Again  */

Four 、 Arrays and slices

package class01

import "testing"

// Declaration of arrays 
func TestOne8_1(t *testing.T) {
    
   var a [3]int
   a[0] = 1    // Subscripts are also from 0 Start 
   t.Log(a[0]) // Print the assignment just now 
   t.Log(a[1]) // Check the part without assignment , Discovery doesn't go wrong ,int type   The default value will be given 0

   n := 3
   //t.Log(a[3]) // Writing directly will report an error 
   t.Log(a[n]) // Direct inspection will report an error , Access is not allowed to cross the border 

   // What default value does the string type give ?
   var b [3]string
   t.Log(b[0]) // The default values are given ""

   // The second way to declare an array 
   c := [3]int{
    1, 2, 3}
   t.Log(c[0])

   // Declaration of multidimensional arrays 
   //d := [2][2]int{1, 2, 3, 4} // It is not allowed to be like c In this way 
   d := [2][2]int{
    {
    1, 2}, {
    3, 4}}
   t.Log(d[0])

   // The declaration method of indefinite array length 
   e := [...]int{
    1, 2, 3, 4, 5}
   t.Log(e[3])
}

// Traversal of array 
func TestOne8_2(t *testing.T) {
    
   arr := [...]int{
    1, 2, 3, 4, 5}

   // Traditional traversal 
   for i := 0; i < len(arr); i++ {
    
      //{  Force code format , If you write to the next line, you will report an error ,expected '{', found newline
      t.Log(arr[i])
   }
}

func TestOne8_3(t *testing.T) {
    
   arr := [...]int{
    1, 2, 3, 4, 5}
   //range Traverse 
   for index, item := range arr {
    
      t.Logf(" The first %d The element is %d", index, item) // Format input and output , Follow c equally 
   }

   // We often don't pay attention to this index Value , however range Two more , We can go through _ Receive 
   for _, item1 := range arr {
    
      t.Log(item1)
   }
}

 Insert picture description here
Inside the array

  • The pointer
  • Element number
  • The capacity of the internal array
package class01

import "testing"

// Array truncation 
func TestOne9_1(t *testing.T) {
    
   // The summary is the pre inclusion , Not included after 
   a := [...]int{
    0, 1, 2, 3, 4, 5}
   t.Log(a[1:2])      //[1]
   t.Log(a[1:3])      //[1 2]
   t.Log(a[1:len(a)]) //[1 2 3 4 5]

   t.Log(a[1:]) // Do not write default is  len(a) [1 2 3 4 5]
   t.Log(a[:3]) // Do not write default is 0 [0 1 2]

   // It is not allowed to have -1, That kind of coquettish thing 
   //t.Log(a[0:-1])

   /*  Section summary : 1、 The essence of internal implementation is a structure , There are three properties  -  Array pointer ptr -  The number of data len(int) -  The capacity of the internal array cap (int) */
}

// How to declare a slice ?
func TestOne9_2(t *testing.T) {
    
   var sl []int // In this way, the length is not declared , It's just a slice , It is   Variable length 
   t.Log(len(sl), cap(sl))

   sl = append(sl, 1)
   t.Log(len(sl), cap(sl))

   sl = append(sl, 2, 3)
   t.Log(len(sl), cap(sl))

   s2 := []int{
    1, 2, 3, 4}
   t.Log(len(s2), cap(s2))

   s3 := make([]int, 3, 5)
   t.Log(len(s3), cap(s3))
   t.Log(s3[0], s3[1], s3[2])
   //t.Log(s3[0], s3[1], s3[2], s3[3], s3[4]) // Last 2 A false report , Tell us that the subscript is out of bounds 
   // therefore ,cap It represents the whole capacity ,len Indicates the currently available range 
}

// Test slice growth 
func TestOne9_3(t *testing.T) {
    
   s := []int{
    }
   for i := 0; i < 10; i++ {
    
      s = append(s, i)
      t.Log(len(s), cap(s))
   }
   //Java Of vector be similar , Automatically expand when the capacity is insufficient , And is x2 growth 
}

// Slice the understanding of shared memory 
func TestOne9_4(t *testing.T) {
    
   arr := [10]int{
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
   slice1 := arr[:5]
   slice2 := arr[3:]
   t.Log(slice1)
   t.Log(slice2)

   // If I modify the original array arr Of arr[3], The contents of the two slices will also be modified , In essence, you still need to understand the underlying implementation of slicing 
   arr[3] = 11
   t.Log(slice1)
   t.Log(slice2)
}

5、 ... and 、Map Statement of 、 Element access and traversal

package class01

import (
   "testing"
)

//map Statement of 
func TestOne10_1(t *testing.T) {
    
   var myMap1 map[string]string // Just declare that there is no room 
   if myMap1 == nil {
    
      t.Log("myMap1  It's an empty map")
   }

   myMap1 = make(map[string]string, 10)
   myMap1["one"] = "java"
   myMap1["one1"] = "java1"
   myMap1["one2"] = "java2"
   myMap1["one3"] = "java3"
   myMap1["one4"] = "java4"
   t.Log(myMap1)
   t.Log(myMap1["one3"])

   // The second way   Use make Function to declare 
   myMap2 := make(map[int]string)
   myMap2[1] = "java"
   myMap2[2] = "java2"
   myMap2[3] = "java3"
   myMap2[4] = "java4"
   t.Log(myMap2)
   t.Log(len(myMap2))

   // The third way 
   myMap3 := map[string]string{
    
      "one":   "php",
      "two":   "java",
      "three": "python",
   }
   t.Log(myMap3)
   t.Logf("myMap3 Is the length of the %d", len(myMap3))

   // ask : Why? map No initialization required len? It only needs cap?
}

//map Common operations 
func TestOne10_2(t *testing.T) {
    
   var myMap1 map[int]int
   var myMap2 map[string]string

   t.Log(myMap1[0])    //0
   t.Log(myMap2["no"]) //""

   // We found that go Will give us one map The default value of , If this doesn't exist key Words , If I really saved one 0 or "" Well ? How to determine ?
   // Actually go In language map Value ,m[0] Is to return two variables , The first is value, The second is bool, Existence as true, There is no such thing as false
   if v, exist := myMap1[0]; exist {
     // Print this value if it exists 
      t.Log(v)
   } else {
    
      t.Log(" This key non-existent ")
   }

   //myMap1[2] = 0
   //t.Log(myMap1[2]) // Will report a mistake , because myMap1 Just a statement , No open control 

   myMap1 = make(map[int]int)
   myMap1[2] = 0
   t.Log(myMap1[2])

   delete(myMap1, 2) // Delete operation 
}

//map The traversal 
func TestOne10_3(t *testing.T) {
    
   myMap3 := map[string]string{
    
      "one":   "go",
      "two":   "java",
      "three": "python",
   }

   for k, v := range myMap3 {
    
      t.Logf("key yes %s,value yes %s", k, v)
   }
}
package main

import "fmt"

func printMap(cityMap map[string]string)  {
    
   //map Transmission is   The essence is also value transfer , The reason is that the structure is copied , The pointer inside the structure does not change , It looks like reference passing 
   for s, s2 := range cityMap {
    
      fmt.Println("key = ",s)
      fmt.Println("value = ",s2)
   }
}

func main() {
    
   cityMap := make(map[string]string)

   // add to 
   cityMap["china"] = "beijing"
   cityMap["amaircan"] = "niuyue"
   cityMap["japan"] = "tokyo"

   // Traverse 
   printMap(cityMap)
   
   // When map When a value obtained in does not exist , Will return the default value 0
   
   
   // Delete 
   delete(cityMap,"china")

   // modify 
   cityMap["amaircan"] = "henan"
   fmt.Println("----------")

   // Traverse 
   for key, value := range cityMap {
    
      fmt.Println("key = ",key)
      fmt.Println("value = ",value)
   }
}

6、 ... and 、 stay Go To realize Set aggregate

Go There is no Set, But it can. map[type] bool
Is to use keys as storage units , The internal value is regarded as a valid flag

package class01

import "testing"

func TestOne11_1(t *testing.T) {
    
   //go There is no native support in the language set, It's through map Deformation operation production   Use map[type] bool
   set1 := map[string]bool{
    }

   // New ways 
   set1["qsr"] = true
   set1["wxy"] = true

   // How to delete 
   set1["qsr"] = false

   // It's essentially passing map Of key The only way to implement 
}

// By the way ,Map And the implementation of factory mode 
func TestOne11_2(t *testing.T) {
    
   m := map[int]func(op int) int{
    } // Define a map,key yes int,value It's a function func, The argument to this function is op int type , The return value is int
   m[1] = func(op int) int {
     return op }
   m[2] = func(op int) int {
     return op * op }
   m[3] = func(op int) int {
     return op * op * op }
   t.Log(m[1](2), m[2](2), m[3](2))
}

7、 ... and 、 character string

 Insert picture description here

package class01

import "testing"

func TestOne12_1(t *testing.T) {
    
   var s string
   t.Log(s)

   s = "hello"
   t.Log(len(s))

   //s[1] = '3' //go in ,string It's immutable , as a result of string The implementation of type is essentially byte Type of slice

   s = "\xE4\xB8\xA5" // Can store any binary data 
   t.Log(s)
   t.Log(len(s)) // The output is byte Count , It's not simple Chinese *2 The length of 
}

func TestOne12_2(t *testing.T) {
    
   // contrast Unicode and UTF8 The difference between 
   s1 := " in "
   t.Log(len(s1))

   c := []rune(s1)
   t.Log(len(c))

   t.Logf(" in   Of Unicode %x", c[0])
   t.Logf(" in   Of UTF8 %x", s1)

   /* Unicode Is a coding rule  UTF8 Is the storage rule  */
}

// Traversal of string 
func TestOne12_3(t *testing.T) {
    
   s := " The People's Republic of China "
   for _, c := range s {
    
      t.Log(c)
      t.Logf("%[1]c %[1]x %[1]d", c) // %[1]  The representation corresponds to the first parameter 
   }
}
  • Common string libraries
     Insert picture description here
package class01

import (
   "strconv"
   "strings"
   "testing"
)

// String segmentation   and   Merge 
func TestOne13_1(t *testing.T) {
    
   s := "a:b:c"
   parts := strings.Split(s, ":")
   for _, ch := range parts {
    
      t.Log(ch)
   }
   t.Log(strings.Join(parts, "-"))
}

// String type conversion 
func TestOne13_2(t *testing.T) {
    

   // Cast a number to string type 
   s := strconv.Itoa(10)
   t.Log("str:" + s) // Strings can be directly +

   // take string Type cast to int
   if n, err := strconv.Atoi("10"); err == nil {
    
      t.Log(n)
   }
}

8、 ... and 、 function

 Insert picture description here

1、 Functional programming

package class01

import (
   "fmt"
   "math/rand"
   "testing"
   "time"
)

// Functions with multiple return values 
func returnMuliValues() (int, int) {
    
   return rand.Intn(10), rand.Intn(20)
}

func TestOne14_1(t *testing.T) {
    
   a, b := returnMuliValues()
   t.Log(a, b)
   a, _ = returnMuliValues()
   t.Log(a)
}

// Calculation method duration , The use of decorators 
func timeSpent(inner func(op int) int) func(op int) int {
     // Declare that an input parameter is a function , The return value is also a function method 
   return func(n int) int {
    
      start := time.Now()
      ret := inner(n) // It is equivalent to executing the function in the input parameter in the middle 
      fmt.Println(" Total function execution time ", time.Since(start).Seconds())
      return ret
   }
}

func slowFun(op int) int {
    
   time.Sleep(time.Second * 1)
   return op * 3
}

func TestOne14_2(t *testing.T) {
    
   res := timeSpent(slowFun) //res function , Is the function after decoration , The return value still retains the original value , Of course, it can also be changed 
   t.Log(res(3))
}

2、 Variable parameters and defer Usage of

 Insert picture description here
Will be converted into an array , Finally, through array traversal

  • defer: In any case, it will be implemented finally
    It can be used to safely release resources , Release lock, etc
package class01

import (
   "fmt"
   "testing"
)

// Functions with variable parameters 
func Sum(ops ...int) int {
    
   resu := 0
   for _, v := range ops {
    
      resu += v
   }
   return resu
}

func TestOne15_1(t *testing.T) {
    
   t.Log(Sum(1, 2, 3))
   t.Log(Sum(1, 2, 3, 4, 5))
}

//defer Usage of 
func DeferDemo() {
    
   fmt.Println(" Yes defer")
}

func TestOne15_2(t *testing.T) {
    
   defer DeferDemo()
   fmt.Println("run now")
   panic("e")
}

/* defer summary  1、 It will be carried out  2、 It must be executed before termination  3、 Even if it's panic Collapse will not affect , Be similar to try catch Medium finally, It will be carried out   use : Safely release resources , Release lock, etc  */
原网站

版权声明
本文为[Li Yian QSR]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207040740327156.html