Last active
May 24, 2021 19:19
-
-
Save aboglioli/cfcd74aacf58dfc44fbfe20cb6b32fd7 to your computer and use it in GitHub Desktop.
Repository with items and save method replacing existing values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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