Hi there! ¿How you doing?
I'm trying to implement a simple in-memory storage, that holds entities under a map. The entities shall be identificables, as they have an Id. And I want that id to be set by the underlying persistent subsystem on creation time. So I wrote this
type Identificable interface {
GetId() int
SetId(id int)
}
type EntitiesMemoryRepository[E Identificable] struct {
entitiesById map[int]E
idSequence int
mutex sync.Mutex
}
func (repo *EntitiesMemoryRepository[E]) CreateEntity(entity E) (E, error) {
repo.mutex.Lock()
defer repo.mutex.Unlock()
nextId := repo.idSequence + 1
entity.SetId(nextId)
repo.entitiesById[nextId] = entity
repo.idSequence++
return entity, nil
} // my in memory db implementation doesn't generate any error, but a external db may arise any kind of errorThe problem arises when I try to use it... as the entity must be mutable I need to work with pointers, right? So I do this:
type User struct {
Id int
Name string
}
func (user User) GetId() int {
return user.Id
}
func (user *User) SetId(id int) {
user.Id = id
}
func main() {
repo := repositories.NewEntitiesMemoryRepository[*User]()
user := User{Name: "John"}
cu, err := repo.CreateEntity(&user)
if err != nil {
panic(err)
}
fmt.Printf("%+v %T\n", cu, cu)
createdUser, err := repo.GetEntityById(1)
if err != nil {
panic(err)
}
fmt.Printf("%+v %T\n", createdUser, createdUser)
}
And everything goes all right.
I just keep wondering if that is correct approach, and, in any case, if any of you guys have reach a similar scenario and how do you solve it. I guess I'm looking for opinions.
Well that would be all, thanks in advance!
Greetings
V