Go

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

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: 
mihalis's picture

GOOS + GOARCH combinations

If you want to see all valid OS/architecture pairs in Go, you should execute the following command:

$ go tool dist list

The output will be like the following:

aix/ppc64
android/386
android/amd64
...

(The GOOS value is first and the GOARCH value is second)

Tags: 

Pages

Subscribe to RSS - Go