lundi 9 mai 2016

How can I use interfaces to allow for more than 1 struct type to make code more useable?

I have a struct that looks like this:

type BetaKey struct {
    Id           int64  `json:"-"`
    IssuerId     int64  `json:"-"          db:"issuer_id"`
    SubjectEmail string `json:"-"          db:"subject_email"`
    IssuedTime   int64  `json:"-"          db:"issued_time"`
    ExpiryTime   int64  `json:"expiryTime" db:"expiry_time"`
    Betakey      string `json:"accessKey"`
    Description  string `json:"description"`
}

And within the same package I have a function that returns a slice of BetaKey:

func buildResults(query string) ([]BetaKey, error) {
    results := []BetaKey{}
    rows, err := sql.DB.Queryx(query)
    if err != nil {
        return results, err
    }
    defer rows.Close()
    for rows.Next() {
        var bk BetaKey
        err := rows.StructScan(&bk)
        if err != nil {
            return results, err
        }
        results = append(results, bk)
    }
    err = rows.Err()
    if err != nil {
        return results, err
    }
    return results, nil
}

Is it possible for me to rewrite this function so that it takes in a query string but also a type of BetaKey as interface{}, and returns a slice of interface{} so that I can reuse the code instead of copy pasting this into every package because it is literally the same but the only difference is the name of the struct that changes.

Is this possible? And also is this advised? If not, then why?





Aucun commentaire:

Enregistrer un commentaire