6, Functions, packages, and error handling

Basic syntax of 1-function

var f1 float64 = 12.34
   var f2 float64 = 12.00
   var oper byte = '-'
   result := cal(f1, f2, oper)
   fmt.Println(result)
}

func cal(n1 float64, n2 float64, operator byte) float64 {
   var res float64
   switch operator {
   case '+':
      res = n1 + n2
   case '-':
      res = n1 - n2
   case '*':
      res = n1 * n2
   case '/':
      res = n1 / n2
   default:
      fmt.Println("Operation symbol error")
   }
   return res
}

2-Pack

Each file of go belongs to a package, that is to say, go manages the file and project directory structure in the form of package

1 - function of package

  1. Identifiers that distinguish functions and variables with the same name
  2. Management project
  3. Control the access scope of functions and variables, i.e. scope

2 - description of the package

Package name

Path to Import package

  1. The package name is usually the same as the file name, which is lowercase
  2. The first line includes package and import
  3. When importing packages, the path starts from src of $GOPATH. Without src, the compiler will automatically import from src
  4. Access functions or variables of other packages, package name Function name or package name Variable name
  5. If the package name is too long, you can take an alias, but the original package name cannot be used
  6. There cannot be two functions with the same name and global variables in the same package
  7. If you want to compile into an executable program file, you need to declare the package as main, that is, package main. This is a syntax specification. If you write a library, the package name can be customized
  8. When compiling, you need to compile the folder where the main package is located[ root@localhost learn]# go build -o bin\my. exe go_ codee\fundemo01\main

3-function

1-function calling mechanism

Description of the above figure:

  1. When calling a function, a new space will be allocated to the function, and the compiler will distinguish this new space from other stack spaces through its own processing
  2. In the stack corresponding to each function, the data space is independent and will not be confused
  3. When a function is called (executed), the program will destroy the stack space of the function

2-return statement

  1. If multiple values are returned and you want to ignore a return value when receiving, use_ The symbol indicates that the placeholder is ignored
  2. If there is only one return value, the return value type list may not be written ()

3 - recursive call of function

A function calls itself in the function body, which is called recursive call

Analysis diagram

case

Summary of recursive calls

  1. When a function is executed, a new protected independent space (new function stack) is created
  2. The local variables of the function are independent and will not affect each other
  3. Recursion must approach the condition of exiting recursion, otherwise it is infinite recursion
  4. When a function is executed or returns, it will be returned to whoever calls it. After the function is executed, it will be destroyed by the system

Exercises

  1. Fibonacci number 1,1,2,3,5,8,13. Give an integer n and return its Fibonacci number
func fbn(n int) int {
   if n == 1 || n == 2 {
      return 1
   } else {
      return fbn(n-1) + fbn(n-2)

   }
}
  1. Find function value

f(1)=3

f(n)=2*f(n-1)+1

func fbn(n int) int {
   if n == 1 {
      return 3
   } else {
      return f(n)=2*f(n-1)+1

   }
}
  1. The problem of monkeys eating peaches

There was a pile of peaches. The monkey ate half of them on the first day and ate another one! After that, monkeys eat half of them every day, and then eat one more. On the tenth day, when I wanted to eat again (I haven't eaten yet), I found that there was only one peach. Question: how many peaches were there in the beginning?

Train of thought analysis:

  1. There was only one peach on the 10th day
  2. How many peaches are there on day 9 = (number of peaches on day 10 + 1) * 2
  3. Rule: Peach data on day n peach(n) = (peach(n+1) + 1) * 2 Code:
func peach(n int) int {
   if n > 10 || n < 1 {
      fmt.Println("Wrong number of days")
      return 0
   }
   if n == 10 {
      return 1
   } else {
      return (peach(n+1) + 1) * 2
   }
}

4-precautions and details of function use

  1. The formal parameter list of a function can be multiple, and the return value list can also be multiple.
  2. The data types of formal parameter list and return value list can be value type and reference type.
  3. The naming of functions follows the identifier naming standard. The first letter cannot be a number. There is a problem with the case of the first letter
  4. The variables in the function are local and do not take effect outside the function
  5. Basic data types and arrays are passed by value by default, that is, value copying. Modification in the function will not affect the original value
  6. If you want the variable inside the function to modify the variable outside the function (referring to the data type passed by value by default), you can pass in the address &, and operate the variable in the function in the form of pointer. In effect, similar references
  7. Go function does not support function overloading (two functions with the same name and different number of parameters are considered to be the same function)
  8. Function is also a data type. If it can be assigned to a variable, the variable is a variable of function type, through which the function can be called
  9. Since the function is a data type, in Go, the function can be used as a formal parameter and called
  10. Use_ Identifier, ignoring return value
  11. Support naming function return value
  12. To simplify data type definition, Go supports custom data types

[basic syntax: type user defined data type name data type]

  1. Go supports variable parameters

  1. If there are variable parameters in the formal parameter list of a function, the variable parameters need to be placed at the end of the formal parameter list.
13-----Go Support variable parameters
func main(){
    res4 := sum(10, 0, -1, 90, 10)//109
   fmt.Println(res4)
}

func sum(n1 int, args ...int) int {
   sum := n1
   for i := 0; i < len(args); i++ {
      sum += args[i]
   }
   return sum
}

12------Go Support custom data types
 Equivalent to alias
 But with the original int There are two types, which need to be converted
type myInt int
var num1 myInt
var num2 int
num1 = 48
num2 = int(num1)
fmt.Println("num1=", num1, "num2=", num2)

Function alias
func main(){
    res3 := myFun2(getSum, 56, 60) 
    fmt.Println(res3) 
} 

type myFunType func(int, int) int 

func myFun2(funvar myFunType, num1 int, num2 int) int { 
        return funvar(num1, num2) 
} 

func getSum(n1 int, n2 int) int { 
        return n1 + n2 
}

11-----Support naming function return value
 func main(){
   a, b := getSumAndSub(1, 2)
   fmt.Println(a, b)
}

func getSumAndSub(n1 int, n2 int) (sum int, sub int) {
   sub = n1 - n2
   sum = n1 + n2
   return
}

If you want the variables inside the function to modify the variables outside the function, you can pass in the address &, and operate the variables in the function in the form of pointers. In terms of effect, similar references

--------------------------------------------
num := 14
test1(num)
fmt.Println(num) //14

func test1(n int) {
   n = n + 10
   fmt.Println(n)//24
   //return 0
}
---------------------------------------------
//Incoming address modification value
func main(){
    num := 14
   //test1(num)
   test3(&num)
   fmt.Println("main num=", num)//24

}

//n is the * int type
func test3(n *int) {
   *n = *n + 10
   fmt.Println("test03 n=", *n)//24
}
//*Value
//&Take address
---------------------------------------------
Function is also a type
func main(){
        a := getSum 
        fmt.Printf("a The type of is%T,getSum Type is%T\n", a, getSum) 

        res := a(10, 40) 
        fmt.Println(res) 
} 

func getSum(n1 int, n2 int) int { 
        return n1 + n2 
}
-----------------------------------------------
Since a function is a type, it can also be used as a parameter
func main(){
   res2 := myFun(getSum, 50, 60)
   fmt.Println(res2)
}

func getSum(n1 int, n2 int) int {
   return n1 + n2
}

func myFun(funvar func(int, int) int, num1 int, num2 int) int {
   return funvar(num1, num2)
}

case

  1. If the type of the first parameter is the same as that of the second parameter, the first one can be followed without parameters

Swap the position of two values

 func main(){
   a = 10
   b = 20
   swap(&a, &b)
   fmt.Printf("a=%v,b=%v", a, b)
}

func swap(n3 *int, n4 *int) {
   t := *n3
   *n3 = *n4
   *n4 = t
}

4-init function

Each source file can contain an init function, which will be called by the Go run framework before the main function is executed

That is, init will be called before the main function.

package main

import "fmt"

func init() {
   fmt.Println("init...")
}

func main() {
   fmt.Println("main...")
}
//GOROOT=D:\go #gosetup 
init... 
main... 

Notes and details of 1-inti function

  1. If a file contains the global variable definition, init function and main function at the same time, the global variable definition of the executed process - > init

Function - > mainfunction

var age = test()

func test() int {
   fmt.Println("test()")
   return 90
}
func init() {
   fmt.Println("init...")
}

func main() {
   fmt.Println("main...", age)
}

//
test() 
init... 
main... 90
  1. The main function of init function is to complete some initialization work (even the imported package)

5-anonymous function

Go supports anonymous functions. Anonymous functions are functions without names. If we want to use a function only once, we can test it

Considering the use of anonymous functions, anonymous functions can also be called multiple times.

5-1 anonymous function usage 1

The anonymous function can be called directly when it is defined. In this way, the anonymous function can only be called once

func main() {
   res1 := func(n1, n2 int) int {
      return n1 + n2
   }(10, 20)//call
   fmt.Println(res1)
}

5-2 anonymous function usage 2

The anonymous function is assigned to a variable (function variable), and then the anonymous function is called through this variable

func main() {
   a := func(n1, n2 int) int {
      return n1 - n2
   }
   res2 := a(10, 5)
   fmt.Println(res2)

   res3 := a(12, 6)
   fmt.Println(res3)
}

5-3 global anonymous function

If you assign an anonymous function to a global variable, the anonymous function becomes a global anonymous function, which can be used in the program

Effective.

var (
   //fun1 is the global anonymous function
   Func1 = func(n1, n2 int) int {
      return n1 + n2
   }
)

6-closure

Basic introduction: a closure is a whole (entity) composed of a function and its related reference environment

case

func AddUpper() func(int) int {
   var n int = 10
   return func(x int) int {
      n = n + x
      return n
   }
}

func main() {
   f := AddUpper()
   fmt.Println(f(1))
   fmt.Println(f(2))
   fmt.Println(f(3))
}

//
11 
13 
16

----This part belongs to closure----
  var n int = 10
   return func(x int) int {
      n = n + x
      return n
   }
--------------------
Returns an anonymous function, But this anonymous function is referenced outside the function n ,So this anonymous function is the same as n Form one
 A whole constitutes a closure
  1. AddUpper is a function that returns a data type of fun (int) int
  2. Closures are classes, functions are operations, and n is a field. Function and its use to n form a closure
  3. When we call f function repeatedly, because n is initialized once, it will be accumulated every time we call it
  4. The key to making a closure clear is to analyze which variables the returned function uses (references), because the function and the variables it references together constitute a closure
  5. A modification to the above code deepens the understanding of closures
func AddUpper() func(int) int {
   var n int = 10
   var str = "hello"
   return func(x int) int {
      n = n + x
      str += string(36) //36=>$
      fmt.Println("str=", str)
      return n
   }
}

func main() {
   f := AddUpper()
   fmt.Println(f(1))
   fmt.Println(f(2))
   fmt.Println(f(3))
}
//result
str= hello$ 
11 
str= hello$$ 
13 
str= hello$$$ 
16

Case:

  1. Write a function makeSuffix(suffix string) to receive a file suffix (such as. jpg) and return a closure
  2. Call closure to pass in a file name. If the file name has no specified suffix (such as. jpg), the file name will be returned jpg, if it already exists jpg suffix, the original file name is returned
  3. Closure is required
  4. strings.HasSuffix, which can judge whether a string has a specified suffix
func makeSuffix(suffix string) func(string) string {
   return func(name string) string {
      if !strings.HasSuffix(name, suffix) {
         return name + suffix
      }
      return name
   }
}

f1 := makeSuffix(".jpg")
fmt.Println("After file name processing=", f1("winter"))
fmt.Println("After file name processing=", f1("winter.jpg"))
fmt.Println("After file name processing=", f1("winter.avi"))

//
After file name processing= winter.jpg 
After file name processing= winter.jpg 
After file name processing= winter.avi.jpg
  1. The returned anonymous function and the suffix variable of makeSuffix (suffix string) are combined into a closure, because the returned function refers to the suffix variable
  2. Let's experience the benefits of closures. If we use traditional methods, we can easily realize this function, but traditional methods need to pass in suffixes every time, such as jpg, and because a closure can retain a value referenced last time, we can pass it in once and use it repeatedly. You can experience it carefully

7-defer

Why defer

In functions, programmers often need to create resources (such as database connection, file handle, lock, etc.). In order to release resources in time after the function is executed, Go designers provide defer (delay mechanism).

func main() {
   res := sum(10, 20)
   fmt.Println("main4 res=", res)
}

func sum(n1 int, n2 int) int {

   //When it is executed to defer, it will not be executed temporarily, and the statements after defer will be transferred to an independent stack (defer stack)
   //After the function is executed, it will be released from the defer stack in a first in first out manner for execution
   defer fmt.Println("sum3 n1=", n1)
   defer fmt.Println("sum2 n2=", n2)
   res := n1 + n2
   fmt.Println("sum1 res=", res)
   return res
}

//
sum1 res= 30 
sum2 n2= 20 
sum3 n1= 10 
main4 res= 30

Summary:

  1. When go executes a defer, it will not execute the statement after defer immediately, but press the statement after defer into a stack [I temporarily call this stack defer stack for the convenience of lectures], and then continue to execute the next statement of the function
  2. After the function is executed, take out the statements from the top of the stack in turn from the defer stack for execution (Note: follow the stack first in and then out mechanism), so the students see the output order of the previous cases
  3. When defer puts the statement on the stack, it will also copy the relevant values into the stack at the same time
func main() {
   res := sum(10, 20)
   fmt.Println("main4 res=", res)
}

func sum(n1 int, n2 int) int {

   //When it is executed to defer, it will not be executed temporarily, and the statements after defer will be transferred to an independent stack (defer stack)
   //After the function is executed, it will be released from the defer stack in a first in first out manner for execution
   defer fmt.Println("sum3 n1=", n1)
   defer fmt.Println("sum2 n2=", n2)
   //increase
   n1++
   n2++
   defer fmt.Println("sum3 n1=", n1)
   defer fmt.Println("sum2 n2=", n2)
   res := n1 + n2
   fmt.Println("sum1 res=", res)
   return res
}

//

sum1 res= 32 
sum2 n2= 21 
sum3 n1= 11 
sum2 n2= 20 
sum3 n1= 10 
main4 res= 32

The main value of defer is that it can release the resources created by the function in time after the function is executed.

  1. The common practice in golang programming is that after creating resources, for example (opening files, obtaining links to databases, or locking resources), you can execute defer file Close() defer connect. Close()
  2. After defer, you can continue to use to create resources
  3. When the function is completed, the system will take out the statements from the defer stack in turn and close the resources
  4. This mechanism is very simple, and programmers don't have to worry about when to turn off resources.

8-function parameter transfer mode

Value type parameters are value passing by default, while reference type parameters are reference passing by default

  1. Two delivery modes

    1. pass by value
    2. Reference passing

In fact, whether it is value transfer or reference transfer, what is passed to the function is the copy of the variable. The difference is that the value transfer is the copy of the value, and the reference transfer is the copy of the address. Generally speaking, the address copy efficiency is high, because the amount of data is small, and the value copy determines the size of the copied data. The larger the data, the lower the efficiency

2 - value type and reference type

  1. Value types: basic data types: int series, float series, bool, string, array and struct
  2. Reference type: pointer, slice slice, map, pipe chan, interface, etc. are all reference types

2 - Characteristics of value passing and reference passing

  1. If you want the variables inside the function to modify the variables outside the function, you can pass in the address &, and operate the variables in the function in the form of pointers. In terms of effect, similar references
//Incoming address modification value
func main(){
    num := 14
   //test1(num)
   test3(&num)
   fmt.Println("main num=", num)//24

}

//n is the * int type
func test3(n *int) {
   *n = *n + 10
   fmt.Println("test03 n=", *n)//24
}
//*Value
//&Take address

9-variable scope

  1. Variables declared / defined inside a function are called local variables, and the scope is limited to the inside of the function
  2. Variables declared / defined outside the function are called global variables. The scope is valid in the whole package. If its initial letter is uppercase, the scope is valid in the whole program
  3. If the variable is in a code block, such as for / if, the scope of the variable is in the code block
Assignment statements cannot be executed outside a function
package main

import "fmt"
var Age int = 20
Name := "test" //First declare and then assign var Name string / Name = "test". The execution statement needs to be executed in the function body
func main() {
    fmt.Println("name",Name)
}

Classroom practice

var age int = 50         //Other packages are not available
var Name string = "jack" //Other packages available

func main() {
   fmt.Println("age=", age)
   fmt.Println("Name=", Name)
   fmt.Println()
   test()
}

func test() {
   age := 10
   Name := "time"
   fmt.Println("age=", age)
   fmt.Println("Name=", Name)
}

-------------------
age= 50 
Name= jack 

age= 10 
Name= time
//If the variable is in a code block, such as for / if, the scope of the variable is in the code block
for i := 0; i < 10; i++ {
   fmt.Println(i)
}

for i := 0; i < 10; i++ {
   fmt.Println(i)
}
fmt.Println(i) //Undefined

To be used locally
var i int
for i = 0; i < 10; i++ {
   fmt.Println(i)
}

---------------------------
var age int = 50         //Other packages are not available
fmt.Println(age)
test01()
test02()
test03()

func test01() {
   fmt.Println(age)
}

func test02() {//Proximity principle
   age := 12
   fmt.Println(age)
}

func test03() {
   fmt.Println(age)
}

Function classroom connection questions

  1. )Function can have no return value case. Write a function, input an integer from the terminal, and print out the corresponding gold pagoda
  2. Write a function, input an integer (1-9) from the terminal, and print out the corresponding multiplication table
//todo

10 - common system functions of string

  1. Count the length of the string by byte len(str)
  2. String traversal, while dealing with Chinese problems, R: = [] run (STR)
  3. String to integer
  4. Integer to string
  5. String to [] byte
  6. [] byte to string
  7. 10 carry to 2,8,hexadecimal
  8. Finds whether the specified string exists in the string
  9. Counts how many specified substrings a string has
  10. Case insensitive string comparison
  11. Returns the index value of the substring at the first occurrence of the string. If not, - 1: strings Index
  12. Returns the index of the last occurrence of the substring in the string. If not, - 1 is returned
  13. Replace the specified substring with another substring: strings Replace ("go go hello", "go", "go language", n) n can refer to how many you want to replace. If n=-1, it means to replace all
  14. According to a specified character, split a string into a string array: strings Split(“hello,world,ok”,”,”)
  15. Convert the letters of a string to uppercase and lowercase strings ToLower() , strings.ToUpper()
//1 - take the length
str := "hello Beijing"
//The encoding of golang is utf8. ascii characters (words and numbers) occupy one byte and Chinese characters occupy three bytes
fmt.Println("str len=", len(str)) //5+1+3+3=12

//2-Chinese traversal
str2 := "hello Beijing"
r := []rune(str2) //section
for i := 0; i < len(r); i++ {
   fmt.Printf("character=%c\n", r[i]) //Chinese garbled code one Chinese character three characters
}
/**
Character = h
 Character = e
 Character = l
 Character = l
 Character = o
 Character = North
 Character = Beijing
*/
//3-string to integer
str3 := "123"
n, err := strconv.Atoi(str3)
if err != nil {
   fmt.Println("Wrong result", err)
} else {
   fmt.Println("The result is", n)
} //The result is 123

//4-integer to string
m := strconv.Itoa(12345)
fmt.Println("The result is", m) //The result is 12345

//5-String to slice [] byte
var bytes = []byte("hello go")
fmt.Printf("bytes=%v\n", bytes) // [104 101 108 108 111 32 103 111]

//6 - slice [] byte to string
str = string([]byte{97, 98, 99})
fmt.Printf("str=%v\n", str) //str=abc

//7 - decimal to 2, 8, hexadecimal: STR = strconv / / string corresponding to 16, 123, int - > (2)
str = strconv.FormatInt(123, 2)
fmt.Printf("123 The corresponding binary is=%v\n", str) //123 corresponds to binary = 1111011
str = strconv.FormatInt(123, 16)
fmt.Printf("123 The corresponding hexadecimal is=%v\n", str) //123 corresponds to hex = 7b

//8 - find whether the substring is in the specified string: strings Contains("seafood", "foo") //bool
b := strings.Contains("seafood", "sea")
fmt.Printf("b=%v\n", b) //b=true

//9 - count how many specified substrings a string has: strings Count("ceheese", "e") //4
num := strings.Count("ceheeeee", "e")
fmt.Printf("b=%v\n", num) //b=6

//10 - case insensitive string comparison (= = case sensitive): FMT Println(strings.EqualFold("abc", "Abc")) // true
b = strings.EqualFold("abc", "ABc")
fmt.Printf("b=%v\n", b)           //b=true
fmt.Println("result", "abc" == "Abc") //Case sensitive / / the result is false

//12 - returns the index value of the substring for the first time in the string. If not, - 1: strings Index("NLT_abc", "abc") // 4
index := strings.Index("NTL_abcabcabc", "abc")
fmt.Printf("index=%v\n", index) //index=4

//13 - returns the index of the last occurrence of the substring in the string. If not, - 1: strings LastIndex("go golang", "go")
indexL := strings.LastIndex("NTL_abcabcabc", "abc")
fmt.Printf("index=%v\n", indexL) //index=10

//14 - replace the specified substring with another substring: strings Replace ("go go hello", "go", "go language", n)
// N can specify how many you want to replace. If n=-1, it means to replace all
str3 = "go go hello"
str = strings.Replace(str3, "go", "Beijing", -1)
fmt.Printf("str=%v str3=%v\n", str, str3) //STR = Beijing hello str3=go go hello

//15 - split a string into a string array: strings Split("hello,wrold,ok",",")
strArr := strings.Split("hello,hello,test", ",")
for i := 0; i < len(strArr); i++ {
   fmt.Printf("str[%v]=%v\n", i, strArr[i])
   /**
   str[0]=hello
   str[1]=hello
   str[2]=test
   */
}
fmt.Printf("strArr=%v\n", strArr) //strArr=[hello hello test] value copy does not change itself

//16 - convert the letters of the string to case: strings ToLower("Go") // go strings. ToUpper("Go") // GO
str4 := "golang hello"
str4 = strings.ToLower(str4)  //Changed str4
fmt.Printf("str4=%v\n", str4) //str4=golang hello
str4 = strings.ToUpper(str4)
fmt.Printf("str4=%v\n", str4) //str4=GOLANG HELLO
  1. Remove the spaces on the left and right sides of the string strings TrimSpace()
  2. Remove [including spaces] strings from the specified characters on the left and right sides of the string Trim(“!hello! “,”!”)
  3. Remove the specified character on the left of the string: strings TrimLeft(“!hello! “,”!”)
  4. Remove the specified character on the right side of the string: strings TrimRight(“!hello! “,”!”)
  5. Determines whether the string starts with the specified string strings HasPrefix(“ ftp://192.168.1.1","ftp")
  6. Judge whether the string ends with the specified string strings HasSuffix(“ ftp://192.168.1.1/aa","aa") //false
//17 - remove the spaces on the left and right sides of the string: strings TrimSpace(" tn a lone gopher ntrn ")
str = strings.TrimSpace(" tn a lone gopher ntrn ")
fmt.Printf("str=%q\n", str) //str="tn a lone gopher ntrn"

//18 - remove the specified characters on the left and right sides of the string: strings Trim("! hello! ",  " !") //  ["hello"] / / turn the left and right sides!
//And "" are removed
str = strings.Trim("! hello  !! ", " !")
fmt.Printf("str=%q\n", str) //str="hello"

//19 - remove the specified character on the left of the string: strings TrimLeft("! hello! ",  " !") //  ["hello"] / / turn left! And“
//"Remove
str = strings.TrimLeft("! hello! ", " !")
fmt.Printf("str=%q\n", str) //str="hello! "

//20 - remove the specified character on the right of the string: strings TrimRight("! hello! ",  " !") //  ["hello"] / / turn to the right! And“
//"Remove
str = strings.TrimRight("! hello! ", " !")
fmt.Printf("str=%q\n", str) //str="! hello"

//21 - judge whether the string starts with the specified string: strings HasPrefix(" ftp://192.168.10.1 ", "ftp") // true
b = strings.HasPrefix("ftp://192.168.10.1", "ftp")
fmt.Printf("str=%v\n", b) //str=true

//22 - judge whether the string ends with the specified string: strings HasSuffix("NLT_abc.jpg", "abc") //false
b = strings.HasSuffix("NLT_abc.jpg", "abc")
fmt.Printf("str=%v\n", b) //str=false

11 - time and date correlation function (202)

  1. time.Time type, used to represent time

  2. Current time, month, day, hour, minute and second

now := time.Now()
fmt.Printf("now=%v now type=%T", now, now)

//now=2021-03-25 16:40:28.2768429 +0800 CST m=+0.003021201 now type=time.Time

//Get the hour, minute and second of month, day and year
fmt.Printf("year=%v\n", now.Year())
fmt.Printf("month=%v\n", now.Month())
fmt.Printf("month=%v\n", int(now.Month()))
fmt.Printf("day=%v\n", now.Day())
fmt.Printf("Time=%v\n", now.Hour())
fmt.Printf("branch=%v\n", now.Minute())
fmt.Printf("second=%v\n", now.Second())

month=March 
month=3 
day=25 
Time=16 
branch=43 
second=42
  1. Format date time

    1. printf or sprintf (sprintf string)
    2. Use time Format() method

2006-01-02 15:04:05 this string must be written like this!

The following are free to adjust for flexible time combinations

now := time.Now()
fmt.Printf("Current date %d-%d-%d %d:%d:%d\n", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())

datastr := fmt.Sprintf("Current date %d-%d-%d %d:%d:%d\n", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
fmt.Printf("datastr=%v", datastr)

fmt.Printf(now.Format("2006-01-02 15:04:05"))
fmt.Println()
fmt.Printf(now.Format("2006-01-02"))
fmt.Println()
fmt.Printf(now.Format("15:04:05"))
fmt.Println()

---------------------------------------------------------------
Current date: 2021-4-15 19:52:44 
datastr=Current date: 2021-4-15 19:52:44 
2021-04-15 19:52:44 
2021-04-15 
19:52:44

//fmt.Printf(now.Format("2006-02-01 15:04:05"))
  1. Constant of time

It can't be divided, so there are so many constants. You can't use Second /10

const (
   Nanosecond  Duration = 1                  //nanosecond
   Microsecond          = 1000 * Nanosecond  //subtle
   Millisecond          = 1000 * Microsecond //millisecond
   Second               = 1000 * Millisecond //second
   Minute               = 60 * Second        //minute
   Hour                 = 60 * Minute        //hour
)

//time.secod seconds

i := 0
for {
   i++
   fmt.Println(i)
   time.Sleep(time.Second)
   time.Sleep(time.Millisecond*100) //100 ms
}
  1. Unix and UnixNano methods of time (function: obtain random numbers)
    1. Uinx int64 elapsed time from 1970 to the present, in seconds
    2. The time unit of UnixNano from 1970 to now is nanosecond
      1. Returns undefined if the value exceeds int64
fmt.Printf("unix=%v unixnano=%v", time.Now().Unix(), time.Now().UnixNano())
//unix=1616731171 unixnano=1616731171139452200
  1. Classroom exercises on time and date

Statistics function execution time

func main(){
   start := time.Now().Unix()
   fmt.Println(start)

   test01()
   end := time.Now().Unix()
   fmt.Println(end)
   fmt.Printf("implement test01()time consuming%v second", end-start)
}
func test01() {
   str := ""
   for i := 0; i < 10000; i++ {
      str += "hello" + strconv.Itoa(i)
      fmt.Println(str)
   }
}
  1. Built in function

studygolang.com/pkgdoc

  1. len: used to find the length, such as string, array, slice, map and channel
  2. new: used to allocate memory. It is mainly used to allocate value types, such as int, float32,struct... Returns pointers
  3. make: used to allocate memory. It is mainly used to allocate reference types, such as chan, map and slice
Array: v Number of elements in
 Array pointer:*v Number of elements in( v by nil Time panic)
Slice, map: v The number of elements in the; if v by nil,len(v)Is zero
 character string: v Number of bytes in
 Number of uncached channels (columns); if v by nil,len(v)Is zero

The pointer stores an address that points to a value
num1 := 100
fmt.Printf("num1 Type of%T,num1 Value of%v,num1 Address of%v\n", num1, num1, &num1)

num2 := new(int)
//Type of num2 * ine
//Value of num2 = one address a (system assigned)
//Address of num2 = address B pointed to by address A (system allocation)
//Value pointed to by num2 = 0
fmt.Printf("num2 Type of%T,num2 Value of%v,num2 Address of%v", num2, num2, &num2,*num2)

------------------------------------------------------------------
num1 Type of int,num1 Value of 100,num1 Address 0 xc00000a0a0 
num2 Type of*int,num2 Value of 0 xc00000a0a8,num2 Address 0 xc000006030

A variable stores a value with an address

The pointer stores an address A, which corresponds to A value B, and the value itself also has an address C

  1. Go error handling mechanism

func test() {
   //Use defer + recover to catch and handle exceptions
   defer func() {
      err := recover() //recover() is a built-in function that can catch exceptions
      if err != nil {
         fmt.Println("err=", err)
      }
   }()

   num1 := 10
   num2 := 0
   res := num1 / num2
   fmt.Println("res=", res)
}

func main() {
   test()
   fmt.Println("main Method under")
}

----------------------------------------------------------
err= runtime error: integer divide by zero 
main Method under
  1. By default, when a panic occurs, the program exits (crashes)
  2. If we want to: when an error occurs, we can catch the error and handle it to ensure that the program can continue to execute
  3. This leads to the error handling mechanism we want to use
Basic description
  1. The Go language does not support the traditional try... catch... finally processing
  2. The processing methods introduced in Go are: defer, panic, recover
  3. You can throw a panic exception in Go, then catch the exception in defer through recover, and then handle it normally
Use defer+recover to handle errors

8 - custom error

Go program also supports custom errors, using errors New and panic built-in functions.

  1. errors.New("error description") will return a value of error type, indicating an error
  2. The panic built-in function receives a value of interface {} type (that is, any value) as a parameter. Can receive error class

Type variable, output error information, and exit the program

func main() {
   test02()
}

func test02() {
   err := readConf("config2.ini")
   if err != nil {
      panic(err)
   }

   fmt.Println("test02 Continue execution")
}

func readConf(name string) (err error) {
   if name == "config.ini" {
      return nil
   } else {
      return errors.New("Error reading file")
   }
}

Function job

Cycle printing the number of days of the entered month continue realization
 There should be a statement to judge whether the entered month is wrong

Write a function
 Random guessing game:
Randomly generate a 1--100 Integer of
 There are ten opportunities
 If you guessed right the first time, you will be prompted: "genius"
If the second--3 Second guess, prompt "smart"
If section 4-9 Second guess, prompt "general"
If the last guess is right, prompt "guess right"
I didn't guess right once, and the prompt "ha ha"
Write a function to output all prime numbers within 100 (prime numbers are books that can only be divided by 1 and itself). Each line displays 5 and sums them
Write a function to judge whether it is fishing or drying the net
 If the "fishing for three days and drying the net for two days" has been implemented since January 1, 1990, how to judge whether it is fishing or drying the net in a future day
Output lowercase a-z And capitalized Z-A,use for Cycle. Asic code

Keywords: Go

Added by TravisJRyan on Thu, 03 Mar 2022 21:12:41 +0200