Skip to content

Instantly share code, notes, and snippets.

@aboglioli
Last active May 24, 2021 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aboglioli/cfcd74aacf58dfc44fbfe20cb6b32fd7 to your computer and use it in GitHub Desktop.
Save aboglioli/cfcd74aacf58dfc44fbfe20cb6b32fd7 to your computer and use it in GitHub Desktop.
Repository with items and save method replacing existing values
package main
import (
"fmt"
"encoding/json"
)
type ID struct {
ID string
}
type Data struct {
ID ID
Payload string
}
type Repository struct {
Items []*Data
}
func NewRepository() *Repository {
return &Repository {
Items: make([]*Data, 0),
}
}
func (r *Repository) Save(data *Data) error {
for i, item := range r.Items {
if item.ID == data.ID {
// Clone the object
// *item = *data
// Pass a reference
r.Items[i] = data
return nil
}
}
r.Items = append(r.Items, data)
return nil
}
func main() {
repo := NewRepository()
repo.Items = []*Data{
&Data{ID{"entity1"}, "data1"},
&Data{ID{"entity2"}, "data2"},
&Data{ID{"entity3"}, "data3"},
&Data{ID{"entity4"}, "data4"},
}
// newItem := &Data{ID{"entity5"}, "data5"}
newItem := &Data{ID{"entity2"}, "data5"}
repo.Save(newItem)
newItem.Payload = "new_data"
s, _ := json.MarshalIndent(repo.Items, "", " ")
fmt.Printf("%s", s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment