Go learning notes — slice

Time:2020-11-27
  1. Delete the last value of the slice
    scores := []int{1, 2, 3, 4, 5}
    lastIndex := len(scores)-1
    source[:lastIndex]
    scores = scores[:lastIndex]

  2. Create a slice with the bottom array of 10 and length of 0
    scores := make([]int, 0, 10) //cap=10 len=0
    //cap=10 , len=3
    scores := make([]int, 3, 10)
    scores = append(scores, 1)
    //Note that the scores are: [0 000 1]

  1. Swap the positions of index, and lastindex in the slice
    source[index], source[lastIndex] = source[lastIndex], source[index]

  2. Go uses a simple rule to define what types and functions are visible outside the package. If the type or function name begins with a capital letter, it has out of package visibility. If you start with a lowercase letter, it can’t.

  3. Code format: go FMT
    When you are in a project, you can apply formatting rules to the project and all its subdirectories

  4. Go has slightly modified the if statement and supports initialization before the condition statement is evaluated

    if x := 10; count > x {
    ...
    }
  5. Null interface {}
    Because there are no methods for empty interfaces, it can be said that all types implement empty interfaces, and since empty interfaces are implicitly implemented, each type satisfies the null interface contract.
    (personal understanding: empty interface can accept any type)

    type User struck {
     Name string
     Age int
    }
    var user interface{} = User{"wubuze", 20}
  6. Null interface type conversion. (type)
    Use the user in the above example

    u. OK: = user. (user) // converted to struct type
    fmt.Println(u.Name, ok)

This work adoptsCC agreementThe author and the link to this article must be indicated in the reprint

Recommended Today

The actor model is so excellent under distributed high concurrency

Write at the beginning In general, there are two strategies for communicating in concurrent threads: shared data and messaging. One of the biggest problems of concurrent programming with shared data is data condition competition. It’s a headache to deal with all kinds of locks. Most of the traditional popular language concurrency is based on shared […]