Golang List Slice Delete one of the comparison

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Slice can add items dynamically (using the Append () function), but there is no function to delete items. Workaround, you can use slice to remove one or more items, slice is a reference type, there is a pointer, there is not much performance impact, the example is as follows:

Package Main

import "FMT"

Func Main () {
s: = []int{11, 22, 33, 44, 55, 66}//Original slice
I: = 2//Index to delete item
s = append (S[:i], s[i+1:] ...) The last "..." cannot be omitted .

FMT. PRINTLN (s)//Data results [one-off]
}


Some people answer very well:

This can be achieved. However, from the point of view of slice data structure, it is not suitable for delete operation. To throw away the language, only to talk about the data structure, we know that the array deletion will move the elements, the efficiency will be lower. Of course, the array implementation of any language (sequential storage), delete elements can not avoid moving elements.
So, if it would be trivial to delete the middle or the beginning of the element, it is better to choose a linked list such data structure. You can use the map or Container/list package in go.


Let's go to the list:

Write a contain function to determine if a value exists in the list

Func Contains (L *list. List, value string) (bool, *list.   Element) {for E: = L.front (); E! = nil; e = E.next () {if E.value = = Value {return true, E} } return False, nil

Let's just drop the remove interface.


If contain, E: = Contains (L, "xxx"); contain {L.remove (e)}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.