I have a function which works when I return a concrete slice, in this case of type schemas.Transaction. In this code, results is a slice of *schemas.Transaction. I try to cast it as []*schemas.Record
and it fails (ok is false). I get a panic when it executes:
return results.([]*schemas.Record), nil
Here is the function:
func findTransactions(q *db.Query, dbUniqueIdentifier database.DBUniqueIdentifier, cli *client.Client) ([]*schemas.Record, error) {
results, err := cli.Find(context.Background(), ThreadID(dbUniqueIdentifier),
data.TransactionCollection.Name, q, &schemas.Transaction{})
if err != nil {
return nil, err
}
instanceSlice, ok := results.([]*schemas.Record)
if ok {
instance := instanceSlice[len(instanceSlice)-1]
fmt.Println(instance)
}
return results.([]*schemas.Record), nil
}
cli.Find() returns (interface{}, error)
If I have the return value set to '[]*schemas.Transaction` it works fine.
Definition of schemas.Transaction:
type Transaction struct {
ID string `json:"_id"`
DebitAccountID string `json:"debit-account-id"`
CreditAccountID string `json:"credit-account-id"`
Amount float64 `json:"amount"`
Description string
Date time.Time
FiscalYear int
FiscalPeriod int
CreatedAt int64 `json:"created_at"`
}
func (transaction Transaction) RecordID() string {
return transaction.ID
}
Definition of schemas.Record:
type Record interface {
RecordID() string
}
I would like to make the findTransactions
function more generic so it can handle other schemas. If I can make this work, the function calling this one could call RecordID() as the other schemas all support this call.