mihalis's blog

mihalis's picture

Deleting an element from a Go slice

This blog post will present two techniques for deleting an element from an existing Go slice.


package main


import "fmt"


func main() {
aSlice := []int{1, 2, 4, 5, 6, 7}
fmt.Println(aSlice)


// Delete element at index i
i := 3
if i > len(aSlice) {
fmt.Println("Cannot delete element", i)
return
}
aSlice = append(aSlice[:i], aSlice[i+1:]...)
fmt.Println(aSlice)


// Delete element at index i
i = 0
if i > len(aSlice) {
fmt.Println("Cannot delete element", i)
return
}
// Replace element at index i with last element
copy(aSlice[i:], aSlice[i+1:])
// Remove last element
aSlice = aSlice[:len(aSlice)-1]
fmt.Println(aSlice)
}


$ go run deleteSlice.go
[1 2 4 5 6 7]
[1 2 4 6 7]
[2 4 6 7]

mihalis's picture

Please review Python installation on this machine before using this extension

I installed VSCode (Visual Studio Code) on macOS. As I am editing reStructuredText files, I installed a relevant extension. After installing that extension, I was getting the following warning message:

Please review Python installation on this machine before using this extension.

The solution is explained at https://github.com/vscode-restructuredtext/vscode-restructuredtext/issue....

Tags: 
mihalis's picture

Yet another review of Mastering Go, 2nd edition

I learned quite a lot from this book.

The Amazon.com page of the book is here. You can also visit the web page of the book at Packt.

Image: 
mihalis's picture

Another review of Mastering Go, 2nd edition

This is another review of Mastering Go, 2nd edition that understands how and why the book was written.

The Amazon.com page of the book is here. You can also visit the web page of the book at Packt.

Image: 
mihalis's picture

A review of Mastering Go, 2nd edition

This is a review for my book that can be found in Amazon.com.

The Amazon.com page of the book is here. You can also visit the web page of the book at Packt.

Image: 

Pages

Subscribe to RSS - mihalis's blog