Introduction to GO language foundation

Posted by warydig on Mon, 07 Mar 2022 13:04:59 +0100

This article mainly summarizes the basis of Go language and its related special grammar.

  1. Unlike Go build, Go run does not create executables. Therefore, in the development stage, use the command go run. When sharing after development, use Go build.
  2. At the beginning of its creation, Go language was used to develop high flow production system.
  3. In the function written in Go language, the types of parameters and return values are declared.
    func addition(x int, y int) int {
        return x + y
    }
  4. Boolean values can only be true and false, 0 and 1 are not allowed.
  5. Length and type must be specified when declaring an array.
    var bele [4]string
    
    bele[0] = "jogn"
  6. The strconv package provides a complete set of methods for type conversion.
  7. Go is responsible for allocating memory and executing garbage phones. Normal memory usage rules still apply, but there is no need to directly manage memory.
  8. When declaring a variable, if it is not assigned a value, the variable will be assigned a default value of zero. Therefore, in order to determine whether the variable has been assigned, you cannot check whether it is nil, but must check whether it is the default value.
  9. Short variable declarations cannot be used outside functions.
  10. Add & to the variable name signature to get the address of the variable in memory.
    s := "Hello"
    
    fmt.Println(&s) //Hexadecimal of memory address
    
  11. Declare with const.
    const gree string = "Hello"
  12. The function return statement returns multiple comma separated values. When receiving, it is separated by commas at the same time, corresponding in sequence.
  13. A variable number of parameters can be passed in a function, but their types must be the same as those specified in the function signature and must be at the last of the parameter table.
    func sumNumber(numbers... int) int {
        total := 0
        for _, number := range numbers {
            total += number
        }
        return total
    }
  14. A named return value enables a function to assign a value to a named variable before returning.
    //func function name (parameter table) (named variable return type){
    //    Function body    
    //    Named variable = return value
    //    return 
    //}
    
    func bar(x, y int) (a, b, c int){ //Named return value
        sum, sub, mul = x+y, x-y, x*y
        return   //Naked return
    }
    
    func main(){
        d, e := 13, 2
        fmt.Println(bar(d,e)) // 15 11 26
    }
  15. The recursive function has at least two return, calls itself in the ending ruturn, and sets the condition in the function body, then return results.
  16. Go treats functions as a type, so you can assign functions to variables and call them later through variables.
    func an(f func() string) string{
        return f()
    }
    
    func main() {
        fn := func() string{
            return "function called"
        }
        fmt.Println(an(fn))
    }
  17. The switch statement supports the default case that will be executed when other case conditions are not met.
    s := "c"
    
    switch s {
        case "a":
            fmt.Println("xx")
        case "b":
            fmt.Println("xx")
        default:
            fmt.Println("xx")  
    }
  18. for statement traverses the data structure display.
    numbers := []int(1, 2, 3, 4)
    for i, n := range numbers {
        fmt.Println("the index of the loop is", i)
        fmt.Println("the value from the array is", n)
    }
  19. defer enables you to execute another function before it returns.
    func main(){
        defer fmt.Println("1")
        fmt.Println("2")
    } // Output 2 1
    
  20. Print all elements of the array, using the variable name itself.
  21. Slices are similar to arrays, but you can add and remove elements from slices.
    func main(){
        var che = make([]string, 2)
        che[0] = "1"
        che[1] = "2"
        che = append(che, "3") //1 2 3
        che = append(che[:2], che[2+1:]...) //1 2delete index2
        var s = make([]string, 2)
        copy(s, che) //Copy slice
    }
  22. A map is a collection of key value pairs, equivalent to a dictionary in python.
    var p = make(map[string]int)
    
    p["c"] = 2
    delete(p, "c")
  23. By using structs, you can store many different types of data fields in a single variable.
    type mo struct{
        name string
        rating float64
    } //Define a mo structure
    
    var xx mo 
    
    xxx := mo{"x", 10}
  24. When there are many fields, it can improve the maintainability and readability of the code to make each field exclusive, but it is worth noting that in this case, the line where the last data field is located must also end with a comma.
    xxx := mo {
        name: "x",
        rating: "12",     
    }
  25. To access the data fields of an embedded structure, use point notation.
  26.   Zero value in go language
    typeZero value
    Boolean typefalse
    plastic0
    float 0.0
    character string" "
    Pointernil
    functionnil
    Interfacenil
    sectionnil
    passagewaynil
    mappingnil
  27. The Go language has built-in methods that provide custom default values, which can be implemented using constructors.
    type Al struct {
        Time string
        Sound string
    }
    
    func NewAl(time string) Al {
        a := al{
            Time: time,
            Sound: "xdx",
        }
        return al
    }
    //Instead of directly creating the structure Al, use the function NewAl to create it, so that the field Sound contains a custom default value.
  28. To compare structures, we should first see whether their types and values are the same. For structures of the same type, use = = for comparison. For structures of different types, compilation errors will be caused.
  29. To export a structure and its fields, the names of the structure and its fields must start with uppercase letters.
  30. By declaring methods, any instance of the structure can be used.
    type Mo struct {
        Name string
        Rating float64 
    }
    
    func sum(m *Mo) string {
        //code
    }
    
    xx := {"sd","2.3"}
    
    xx.sum() //Method call
    
  31. Any data type can have an associated set of methods. There is no limit to the number of methods a method set can contain, which is an effective way to encapsulate functions and create library code.
  32. The difference between a pointer and a value is subtle, but choosing whether to use a pointer or a value is simple: use a pointer if you need to modify the original structure; If you need to manipulate the structure, but do not want to modify the original structure, use the value.
  33. Interface describes all the methods in the method set and specifies the function signature of each method.
  34. Interface is the blueprint of method set. If you want to use interface, you must implement it first.
  35. Conditions for the same function signature (function name, parameters, return value type, number and order are the same).
  36. An interface is also a type that can be passed as a parameter to a function.
  37. Go language does not provide object-oriented functions such as class and class inheritance, but the structure and method set make up for this deficiency and provide some object-oriented elements.
  38. The interface provides polymorphism in a declarative way, because the interface describes the method set that must be provided and the function signature of these methods. If a method set implements an interface, it can be said that it is polymorphic with another method set that implements the interface.
  39. Strictly speaking, the only difference between a method and a function is that the method has an additional parameter that specifies the recipient.

Topics: Go Back-end