« Back to Index

[Go Array Element Removal]

View original Gist on GitHub

Tags: #go #golang #array #slice #splice #remove #element #item

Go Array Element Removal.go

package main

import (
	"fmt"
)

// Task represents an on-call TODO item.
type Task struct {
	Desc    string
	Done    bool
	Skipped bool
}

// Tasks is a collection of tasks for a specific incident
type Tasks []Task

// Incident is a unique incident consisting of list of checklist tasks.
type Incident struct {
	Name      string
	Checklist Tasks
}

// Incidents is a list of individual incidents that are being monitored.
type Incidents []Incident

// removeIncident resplices the given list of incidents so the index is
// removed by taking individual slices of the data and combining them without
// the specified element index.
func removeIncident(i int, incidents Incidents) Incidents {
	incidentName := incidents[i].Name
	incidents = append(incidents[:i], incidents[i+1:]...)
	fmt.Printf("incident '%s' removed successfully\n", incidentName)
	return incidents
}

// ALTERNATIVE VERSION...
//
// removeIncident resplices the given list of incidents so the index is
// removed. This uses the most performant approach possible, which causes the
// ordering of the slice to change.
//func removeIncident(i int, incidents Incidents) Incidents {
//	incidents[i] = incidents[len(incidents)-1] // Copy last element to index i.
//	incidents[len(incidents)-1] = Incident{}   // Erase last element (write zero value).
//	incidents = incidents[:len(incidents)-1]   // Truncate slice.
//	return incidents
//}

func main() {
	icd := []Incident{
		{Name: "foo", Checklist: []Task{{Desc: "foo happened"}}},
		{Name: "bar", Checklist: []Task{{Desc: "bar happened"}}},
		{Name: "baz", Checklist: []Task{{Desc: "baz happened"}}},
	}

	// remove "bar"
	icd = removeIncident(1, icd)
	fmt.Printf("%v (%d)\n", icd, len(icd))

	// remove "baz"
	icd = removeIncident(1, icd)
	fmt.Printf("%v (%d)\n", icd, len(icd))

	// remove "foo"
	icd = removeIncident(0, icd)
	fmt.Printf("%v (%d)\n", icd, len(icd))
}