Go语言内建方法之append && delete && copy

  • 用来操作变量
  • slice -> append(添加一个元素)

       package main
       import "fmt"
       func main() {
           appendElementSlice()
       }
       func appendElementSlice()  {
            mIDSlice := make([]string, 2)  //要求较高的时候我们需要声明定长(避免操作内存),append会操作内存
            mIDSlice[0] = "id-1"
            mIDSlice[1] = "id-2"
            fmt.Println("追加前的cap(容量)=",cap(mIDSlice)) //追加前的cap(容量)= 2
            fmt.Print("\n")
            mIDSlice = append(mIDSlice,"id-3")  //追加一个元素,扩容
            fmt.Println(mIDSlice)  //[id-1 id-2 id-3]
            fmt.Print("\n")
            fmt.Println("len:",len(mIDSlice)) //len: 3
            fmt.Print("\n")
            fmt.Println("追加后的cap(容量)=",cap(mIDSlice)) //追加后的cap(容量)= 4
       }
  • slice -> copy(复制整个切片,有一定规则)

       package main
       import "fmt"
       func main() {
           copyForSlice()
       } 
       func copyForSlice()  {
           mIDSliceDst := make([]string, 3)
           mIDSliceDst[0] = "id-dst-1"
           mIDSliceDst[1] = "id-dst-2"
           mIDSliceDst[2] = "id-dst-3"
       
           mIDSliceSrc := make([]string, 2)
           mIDSliceSrc[0] = "id-src-1"
           mIDSliceSrc[1] = "id-src-2"
       
           //目标源的长度大于被copy源的长度时取被copy源的长度的值替换相同key的value值
           //目标源的长度小于被copy源的长度时取目标源的长度的值替换相同key的value值
           copy(mIDSliceDst, mIDSliceSrc)
       
           fmt.Println(mIDSliceDst)    //[id-src-1 id-src-2 id-dst-3]
       }
  • map -> delete (删除)

      package main
      
      import "fmt"
      
      func main() {
          deleteFormMap()
      }
      //删除map中的数据
      func deleteFormMap()  {
          mIDMap := make(map[int]string)
          mIDMap[0] = "id-1"
          mIDMap[1] = "id-2"
          mIDMap[2] = "id-3"
          fmt.Println(mIDMap)            //map[0:id-1 1:id-2 2:id-3]
          fmt.Print("\n")
          delete(mIDMap, 0)              //删除指定下标的值
          fmt.Println(mIDMap)            //map[1:id-2 2:id-3]
      }
Last modification:September 23, 2020
如果觉得我的文章对你有用,请随意赞赏