I have an application with a recent addition that requires the removal of a struct pointer from a slice that is itself an element of another struct. A summary of the usage.
I am wondering if this is idiomatic and okay usage of the go languages. Things appear to work and this appears to be inline with the golang recommendations for slice element deletion.
package main
import (
"fmt"
"strconv"
)
const ARBITRARY= 5
type myData struct {
det detailSlicePtr
}
type detail struct {
id int
name string
}
// Slice of pointers to details
type detailSlicePtr []*detail
// Returns true if item removed succesfully,
// false all other cases
func(s *myData ) remove(d *detail) bool {
for i:= range s.det {
if s.det[i].name == d.name && s.det[i].id == d.id {
s.det[i] = new(detail)
s.det = append(s.det[:i],s.det[i+1:]...)
return true
}
}
return false
}
// Find and remove a struct element from a slice of struct pointers within a struct
func main() {
var d myData
details := make(detailSlicePtr , ARBITRARY)
for j := 0; j < ARBITRARY; j++ {
details [j] = &detail{
id: j,
name: strconv.Itoa(j),
}
}
d.det = details
// Print out what we have so far
for index := range d.det {
fmt.Printf("Item %d is %s\n", index, d.det[index].name)
}
findMe := ARBITRARY / 2
middle := &detail{id: findMe ,name:strconv.Itoa(findMe)}
if ok := d.remove(middle); !ok {
fmt.Printf("Unable to find element: %v\n", middle)
} else {
fmt.Printf("Found and removed element: %v\n", middle)
// Print what is left
for index := range d.det {
fmt.Printf("Item %d is %s\n", index, d.det[index].name)
}
}
}