Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: Add comparator for structs #139

Open
ScreamingHawk opened this issue Jul 10, 2024 · 4 comments
Open

Suggestion: Add comparator for structs #139

ScreamingHawk opened this issue Jul 10, 2024 · 4 comments

Comments

@ScreamingHawk
Copy link

What is considered comparable in Go?

  • Structs if all of their fields are also comparable independently

Would be great to be able to pass a key (or function) to for struct comparison instead of relying on complete field equality.

Particularly useful when comparing structs with incomplete data (e.g. from an API) with complete data (e.g. from DB).

@deckarep
Copy link
Owner

Hello,

Thanks for the recommendation! I'm certainly not opposed to changes that would be considered general enough that others would find useful and if you have an API in mind I'd love to hear more details.

This package is so widely used it would be help to get more context and allow others to chime in.

@ScreamingHawk
Copy link
Author

Here's some pseudo code for the pattern I've got. Please forgive errors.

type Entity struct {
  ID        uint64
  Data1 string
  Data2 bool
  // ...
  UpdatedAt *time.Time
}

func Update(apiEntities []*Entity) error {
  dbEntities = db.ListEntities()
  origSet := mapset.NewSet(dbEntities...)
  updateSet := mapset.NewSet(apiEntities...)

  added := updateSet.Difference(origSet)
  // Process newly added entries

  removed := origSet.Difference(updateSet)
  // Process deleted entries
}

Entity's that come in via the API don't have an ID populated, this causes all data to not match.
Also in this case UpdatedAt should be ignored when looking for equality.

If we could pass a function to do the comparison, that would be a nice general solution.
Something like:

func entityEqual(a Entity, b Entity) bool {
  // Whatever logic here
  return a.Data1 == b.Data1 && a.Data2 == b.Data2
}

func Update(apiEntities []*Entity) error {
  // ...
  added := updateSet.Difference(origSet, entityEqual)
  // ...
}

@deckarep
Copy link
Owner

deckarep commented Jul 10, 2024 via email

@deckarep
Copy link
Owner

deckarep commented Aug 4, 2024

@ScreamingHawk - circling back on this seems like this would be a fairly large breaking change. I understand what your concern is but I do feel like this would possibly complicate the API. I'm still thinking about it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants