zoukankan      html  css  js  c++  java
  • golang 2 ways to delete an element from a slice

    2 ways to delete an element from a slice

    yourbasic.org/golang

    Fast version (changes order)

    a := []string{"A", "B", "C", "D", "E"}
    i := 2
    
    // Remove the element at index i from a.
    a[i] = a[len(a)-1] // Copy last element to index i.
    a[len(a)-1] = ""   // Erase last element (write zero value).
    a = a[:len(a)-1]   // Truncate slice.
    
    fmt.Println(a) // [A B E D]

    The code copies a single element and runs in constant time.

    Slow version (maintains order)

    a := []string{"A", "B", "C", "D", "E"}
    i := 2
    
    // Remove the element at index i from a.
    copy(a[i:], a[i+1:]) // Shift a[i+1:] left one index.
    a[len(a)-1] = ""     // Erase last element (write zero value).
    a = a[:len(a)-1]     // Truncate slice.
    
    fmt.Println(a) // [A B D E]

    The code copies len(a) - i - 1 elements and runs in linear time.

  • 相关阅读:
    ThreadLocal
    mysql
    heroku 的用法
    Redis
    disruptor
    RxJava
    TCP
    虚拟机的安装及配置等
    k8s
    Ribbon源
  • 原文地址:https://www.cnblogs.com/oxspirt/p/11273308.html
Copyright © 2011-2022 走看看