3 ms·
func findThing(things []Thing, name string) *Thing { for i := range things { if things[i].Name == name { return &things[i] }
by maerF0x0 2y ago
func findThing(things []Thing, name string) *Thing {
for i := range things {
if things[i].Name == name {
return &things[i]
}
}
return nil
}
Also you could just return i or -1, and the consuming code would be clear about what it was doing. Find the index. Update the item at the index.
if location := findThing(things, name); location != -1 {
things[location].Name = "updated"
}
- Joker_vD 2y agoWell, if you don't mind that it doesn't work correctly with slices: [0], then sure, you may return indices. [0] https://go.dev/play/p/Q2ntuaugbGQ https://go.dev/play/p/Q2ntuaugbGQ
- benmmurphy 2y agoIt does work with slices as long as you use the slice to update as well
- maerF0x0 2y agoThat didn't work because you didn't pass the same slice in. You subsliced your things slice, which outputs a new slice.