Created
February 22, 2023 20:04
-
-
Save coopernurse/a9068cf6445b8cf6e029781f9009e756 to your computer and use it in GitHub Desktop.
sorting embedded struct via generics
This file contains hidden or 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 model | |
type Account struct { | |
Entity | |
Username string `json:"username" dynamodbav:"username"` | |
Name string `json:"name,omitempty" dynamodbav:"name"` | |
Broker string `json:"broker,omitempty" dynamodbav:"broker"` | |
AuthKey string `json:"authkey,omitempty" dynamodbav:"authkey"` | |
BrokerAccountID string `json:"brokeraccountid,omitempty" dynamodbav:"brokeraccountid"` | |
LastSyncMillis int64 `json:"lastsync,omitempty" dynamodbav:"lastsync"` | |
} | |
// this works: | |
func foo() { | |
accts = make([]*model.Account, 5) | |
// code to populate accts redacted | |
SortByID(accts) | |
} |
This file contains hidden or 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 model | |
import ( | |
"sort" | |
"strings" | |
) | |
type Entity struct { | |
Partition string `json:"partition" dynamodbav:"part"` | |
ID string `json:"id" dynamodbav:"id"` | |
CreatedAt int64 `json:"createdAt" dynamodbav:"createdAt"` | |
UpdatedAt int64 `json:"updatedAt" dynamodbav:"updatedAt"` | |
} | |
func (e Entity) GetID() string { return e.ID } | |
func (e Entity) GetCreatedAt() int64 { return e.CreatedAt } | |
func (e Entity) GetUpdatedAt() int64 { return e.UpdatedAt } | |
type IEntity interface { | |
GetID() string | |
GetCreatedAt() int64 | |
GetUpdatedAt() int64 | |
} | |
func SortByID[T IEntity](s []T) { | |
sort.Slice(s, func(i, j int) bool { | |
return strings.Compare(s[i].GetID(), s[j].GetID()) < 0 | |
}) | |
} | |
func SortByCreatedAt[T IEntity](s []T) { | |
sort.Slice(s, func(i, j int) bool { | |
return s[i].GetCreatedAt() < s[j].GetCreatedAt() | |
}) | |
} | |
func SortByUpdatedAt[T IEntity](s []T) { | |
sort.Slice(s, func(i, j int) bool { | |
return s[i].GetUpdatedAt() < s[j].GetUpdatedAt() | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment