-
I need a universal function to retrieve all records from tables.
I would like to call the function this way: in function loadCodeTable, it needs to retrieve all records and returning to a slice
but how can I retrieve all records to a slice of struct Account? I tried reflect, but no help. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @chekaiyin, if I understand correctly, you need a universal The following is what I came up with, not sure if it solves your problem. You can retrieve all records to the func loadCodeTable2(db *bun.DB, codeTable CodeTable) ([]Account, error) {
accounts := make([]Account, 0)
err := db.NewSelect().Model(codeTable).Scan(context.Background(), &accounts)
return accounts, err
} If you need the function to be universal across every type, not just for func loadCodeTable[T any](db *bun.DB, codeTable CodeTable) ([]T, error) {
data := make([]T, 0)
err := db.NewSelect().Model(codeTable).Scan(context.Background(), &data)
return data, err
} You can then use the above generic function for different types of struct, not just for data, err := loadCodeTable[Account](db, (*Account)(nil))
data2, err := loadCodeTable[Person](db, (*Person)(nil)) |
Beta Was this translation helpful? Give feedback.
Hi @chekaiyin, if I understand correctly, you need a universal
loadCodeTable
that can be called on slices of any structs, not justAccount
struct.The following is what I came up with, not sure if it solves your problem.
You can retrieve all records to the
Account
struct by simply passing a reference of the slice to theScan
function like so:If you need the function to be universal across every type, not just for
Account
, you can use Golang generics.