Как удалить элемент из массива golang
A Slice in Golang is an array(list of elements of the same type) but it’s dynamic i.e. it can adjust its size as per the elements added throughout the program. We can initialize a slice without specifying the initial length or size, this allows us to add elements to it dynamically. So, there might be instances, where you need to remove elements from the slice. In Golang, the slice interface doesn’t have a built-in function for deleting elements in slices. So, in this article, we’ll be understanding how to delete elements in a slice.
Deleting Elements in a Slice
To delete an element from a slice, we can’t directly remove an element from it, we need to perform certain copying of all elements in a different location and then relocate them to a new position in the original slice. To do this first we will construct a simple slice, populate it with elements and then delete an element based on its index. Given, the index of elements to delete from the slice, we will append all the elements after that index into a slice that contains all the elements before that index. This append operation will eventually modify the existing slice and remove the element by breaking the original slice into two slices and combining them again.
Using the append function to delete an element
We create a slice and add elements to the slice, now we delete elements from it. So, we are going to delete the element by referencing its index of it in the slice. To delete the elements by referencing, we will first create a variable for storing the index of an element, the index variable can also be taken in the form of input or passed from elsewhere. Using that index variable, we can access elements from the slice as we can see from the following example:
How to delete an element from a Slice in Golang
I am using this command to delete an element from a Slice but it is not working, please suggest.
![]()
20 Answers 20
Order matters
If you want to keep your array ordered, you have to shift all of the elements at the right of the deleting index by one to the left. Hopefully, this can be done easily in Golang:
However, this is inefficient because you may end up with moving all of the elements, which is costly.
Order is not important
If you do not care about ordering, you have the much faster possibility to replace the element to delete with the one at the end of the slice and then return the n-1 first elements:
With the reslicing method, emptying an array of 1 000 000 elements take 224s, with this one it takes only 0.06ns.
This answer does not perform bounds-checking. It expects a valid index as input. This means that negative values or indices that are greater or equal to the initial len(s) will cause Go to panic.
Slices and arrays being 0-indexed, removing the n-th element of an array implies to provide input n-1. To remove the first element, call remove(s, 0), to remove the second, call remove(s, 1), and so on and so forth.
![]()
This is a little strange to see but most answers here are dangerous and gloss over what they are actually doing. Looking at the original question that was asked about removing an item from the slice a copy of the slice is being made and then it’s being filled. This ensures that as the slices are passed around your program you don’t introduce subtle bugs.
Here is some code comparing users answers in this thread and the original post. Here is a go playground to mess around with this code in.
Append based removal
In the above example you can see me create a slice and fill it manually with numbers 0 to 9. We then remove index 5 from all and assign it to remove index. However when we go to print out all now we see that it has been modified as well. This is because slices are pointers to an underlying array. Writing it out to removeIndex causes all to be modified as well with the difference being all is longer by one element that is no longer reachable from removeIndex . Next we change a value in removeIndex and we can see all gets modified as well. Effective go goes into some more detail on this.
The following example I won’t go into but it does the same thing for our purposes. And just illustrates that using copy is no different.
The questions original answer
Looking at the original question it does not modify the slice that it’s removing an item from. Making the original answer in this thread the best so far for most people coming to this page.
As you can see this output acts as most people would expect and likely what most people want. Modification of originalRemove doesn’t cause changes in all and the operation of removing the index and assigning it doesn’t cause changes as well! Fantastic!
This code is a little lengthy though so the above can be changed to this.
A correct answer
Almost identical to the original remove index solution however we make a new slice to append to before returning.
Name already in use
golang-book / _book / chapter-06-arrays-slices-maps.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
В главе 3 мы изучили базовые типы Go. В этой главе мы рассмотрим еще три встроенных типа: массивы, срезы и карты.
Массив — это нумерованная последовательность элементов одного типа с фиксированной длиной. В Go они выглядят так:
x — это пример массива, состоящего из пяти элементов типа int . Запустим следующую программу:
Вы должны увидеть следующее:
x[4] = 100 должно читаться как «присвоить пятому элементу массива x значение 100». Может показаться странным то, что x[4] является пятым элементом массива, а не четвертым, но, как и строки, массивы нумеруются с нуля. Доступ к элементам массива выглядит так же, как у строк. Вместо fmt.Println(x) мы можем написать fmt.Println(x[4]) и в результате будет выведено 100 .
Пример программы, использующей массивы:
Эта программа вычисляет среднюю оценку за экзамен. Если вы выполните её, то увидите 86.6 . Давайте рассмотрим её внимательнее:
- сперва мы создаем массив длины 5 и заполняем его;
- затем мы в цикле считаем общее количество баллов;
- и в конце мы делим общую сумму баллов на количество элементов, чтобы узнать средний балл.
Эта программа работает, но её всё еще можно улучшить. Во-первых, бросается в глаза следующее: i < 5 и total / 5 . Если мы изменим количество оценок с 5 на 6, то придется переписывать код в этих двух местах. Будет лучше использовать длину массива:
Напишите этот кусок кода и запустите программу. Вы должны получить ошибку:
Проблема в том, что len(x) и total имеют разный тип. total имеет тип float64 , а len(x) — int . Так что, нам надо конвертировать len(x) в float64 :
Это был пример преобразования типов. В целом, для преобразования типа можно использовать имя типа в качестве функции.
Другая вещь, которую мы можем изменить в нашей программе — это цикл:
В этом цикле i представляет текущую позицию в массиве, а value будет тем же самым что и x[i] . Мы использовали ключевое слово range перед переменной, по которой мы хотим пройтись циклом.
Выполнение этой программы вызовет другую ошибку:
Компилятор Go не позволяет вам создавать переменные, которые никогда не используются в коде. Поскольку мы не используем i внутри нашего цикла, то надо изменить код следующим образом:
Одиночный символ подчеркивания _ используется, чтобы сказать компилятору, что переменная нам не нужна (в данном случае нам не нужна переменная итератора).
А еще в Go есть короткая запись для создания массивов:
Указывать тип не обязательно — Go сам может его выяснить по содержимому массива.
Иногда массивы могут оказаться слишком длинными для записи в одну строку, в этом случае Go позволяет записывать их в несколько строк:
Обратите внимание на последнюю , после 83 . Она обязательна и позволяет легко удалить элемент из массива просто закомментировав строку:
Срез это часть массива. Как и массивы, срезы индексируются и имеют длину. В отличии от массивов их длину можно изменить. Вот пример среза:
Единственное отличие объявления среза от объявления массива — отсутствие указания длины в квадратных скобках. В нашем случае x будет иметь длину 0.
Срез создается встроенной функцией make :
Этот код создаст срез, который связан с массивом типа float64 , длиной 5 . Срезы всегда связаны с каким-нибудь массивом. Они не могут стать больше чем массив, а вот меньше — пожалуйста. Функция make принимает и третий параметр:
10 — это длина массива, на который указывает срез:

Другой способ создать срез — использовать выражение [low : high] :
low — это позиция, с которой будет начинаться срез, а high — это позиция, где он закончится. Например: arr[0:5] вернет [1,2,3,4,5] , arr[1:4] вернет [2,3,4] .
Для удобства мы также можем опустить low , high или и то, и другое. arr[0:] это то же самое что arr[0:len(arr)] , arr[:5] то же самое что arr[0:5] и arr[:] то же самое что arr[0:len(arr)] .
В Go есть две встроенные функции для срезов: append и copy . Вот пример работы функции append :
После выполнения программы slice1 будет содержать [1,2,3] , а slice2 — [1,2,3,4,5] . append создает новый срез из уже существующего (первый аргумент) и добавляет к нему все следующие аргументы.
Пример работы copy :
После выполнения этой программы slice1 будет содержать [1,2,3] , а slice2 — [1,2] . Содержимое slice1 копируется в slice2 , но поскольку в slice2 есть место только для двух элементов, то только два первых элемента slice1 будут скопированы.
Карта (также известна как ассоциативный массив или словарь) — это неупорядоченная коллекция пар вида ключ-значение. Пример:
Карта представляется в связке с ключевым словом map , следующим за ним типом ключа в скобках и типом значения после скобок. Читается это следующим образом: « x — это карта string -ов для int -ов».
Подобно массивам и срезам, к элементам карт можно обратиться с помощью скобок. Запустим следующую программу:
Вы должны увидеть ошибку, похожую на эту:
До этого момента мы имели дело только с ошибками во время компиляции. Сейчас мы видим ошибку исполнения.
Проблема нашей программы в том, что карта должна быть инициализирована перед тем, как будет использована. Надо написать так:
Если выполнить эту программу, то вы должны увидеть 10 . Выражение x[«key»] = 10 похоже на те, что использовались при работе с массивами, но ключ тут не число, а строка (потому что в карте указан тип ключа string ). Мы также можем создать карты с ключом типа int :
Это выглядит очень похоже на массив, но существует несколько различий. Во-первых, длина карты (которую мы можем найти так: len(x) ) может измениться, когда мы добавим в нее новый элемент. В самом начале при создании длина 0 , после x[1] = 10 она станет равна 1 . Во-вторых, карта не является последовательностью. В нашем примере у нас есть элемент x[1] , в случае массива должен быть и первый элемент x[0] , но в картах это не так.
Также мы можем удалить элементы из карты используя встроенную функцию delete :
Давайте посмотрим на пример программы, использующей карты:
В данном примере elements — это карта, которая представляет 10 первых химических элементов, индексируемых символами. Это очень частый способ использования карт — в качестве словаря или таблицы. Предположим, мы пытаемся обратиться к несуществующему элементу:
Если вы выполните это, то ничего не увидите. Технически карта вернет нулевое значение хранящегося типа (для строк это пустая строка). Несмотря на то, что мы можем проверить нулевое значение с помощью условия ( elements[«Un»] == «» ), в Go есть лучший способ сделать это:
Доступ к элементу карты может вернуть два значения вместо одного. Первое значение это результат запроса, второе говорит, был ли запрос успешен. В Go часто встречается такой код:
Сперва мы пробуем получить значение из карты, а затем, если это удалось, мы выполняем код внутри блока.
Объявления карт можно записывать сокращенно — так же, как массивы:
Карты часто используются для хранения общей информации. Давайте изменим нашу программу так, чтобы вместо имени элемента хранить какую-нибудь дополнительную информацию о нем. Например его агрегатное состояние:
Заметим, что тип нашей карты теперь map[string]map[string]string . Мы получили карту строк для карты строк. Внешняя карта используется как поиск по символу химического элемента, а внутренняя — для хранения информации об элементе. Не смотря на то, что карты часто используется таким образом, в главе 9 мы узнаем лучший способ хранения данных.
Как обратиться к четвертому элементу массива или среза?
Чему равна длина среза, созданного таким способом: make([]int, 3, 9) ?
что вернет вам x[2:5] ?
Напишите программу, которая находит самый наименьший элемент в этом списке:
Delete elements from slice in GO [SOLVED]
In Golang, we deal with slices very often, they are the arrays of other programming languages, and they are used lot in Golang, so one of the tasks we would need, is to delete an element of a slice, and that element might require us to rearrange the slice, or sometimes we dont care, we just want to delete that element, and keep the rest of the slice. This tutorial will explain to you the exact steps you would need to take in order to delete any element of a slice fairly easily.
Delete first element from slice
To delete first element of a slice, we have a simple step, we truncate all elements of the slice, from the index 1 , to the end. in this way we delete element of index 0
We truncate the first element, by starting from index 1, all the way to the end
This takes a constant time to truncate that first element. O(1)
Delete first n elements from slice
If we have a task to delete a number of elements n, in a slice we would do the thing, but with defining from where we start our deletion.
We would of course need to make sure, the value we are providing as n, is within an acceptable range. feel free to manipulate that, because if you don’t check, you might run to a panic situation, if you try to delete more elements than what the slice does have.
This takes a constant time to truncate that n element. O(1)
Delete last element from slice
Deleting the last element of the slice, is a similar operation to deleting from the end, except we change the range of the slice we want so
This takes a constant time to truncate that last element. O(1)
Delete last n elements from slice
Again we might need to delete n elements from a slice, we would need to do the same operation, but we do a checking whether that keeps our manipulation in the range or not, in case a slice of 10 elements and you want to delete 20 elements, a panic will be thrown, that’s way I would return the slice as is. without manipulation, feel free to change that for your needs
Delete random elements from slice
To delete a random element from a slice, we first need to generate a random number, between the length of the slice, and 0 as its first element, then we use that as the element we want to delete. then we shift the elements of the slice in the same order, by re-appending them to the slice, starting from the next position from that index
- We generate a random integer, that is the index we will delete, the index range is from 0 to the last element of the slice.
- We shift all elements of the slice who are after that element
This takes a linear time to delete the random element. O(n) because we are shifting all the elements after it. and keeping the order
Delete element of a slice based on its position (index number)
We can delete elements from a slice, by the index, but we can do that, in two different ways.
Without keeping the order
So given we have a slice, and we try to get ride of an element, we know its index, we what we can do, is to assign the last element of the slice, and duplicate it, in the same position, of the element we want to delete, then we basically would have the same slice, except this element, being stamped by the last element of the slice. Then we simply truncate the slice, and take all the slice except the last element. let me show you
- We stamp the element last element, in the element we want to delete
- We then truncate the slice, and take all elements except the last one
The time complexity of this approach is O(1) time. so constant time.
Keeping the slice order
If maintaining the order is important to us, we have to do a different approach. we need to shift, by making a copy of all elements of the slice, that after the element we want to delete, by which gain, the last element will be a duplicated one, as we wont touch to it.
Then we just truncate the slice.
- We copy (shift) the elements of the slice who come after the one we want to delete, starting from the one we want to delete, so last element will be a duplicate
- We truncate the last element
The time complexity of this approach is O(n) time. because of the copy step. Linear time.
Deleting n elements from the slice, starting from an index
as we can shift or copy elements of a slice, we can delete n elements from the slice by using this last method, where keep the order, we simply would need the index our starting point, and the number of elements we want to delete
- We first check for the n wether its in the range of the slice.
- We then copy all the elements after index + n
- Then we truncate the n number of elements.
The time complexity of this approach is O(n) time. because of the copy step. Linear time.
Conclusion
Slices manipulation, is one critical thing to learn, and this tutorial should clarify any deletion operation you need for your next project. Use each technique for its purpose with maximum performance.
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.