Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert []interface{} to custom defined type - Go lang?

Tags:

go

I am started working in Go. Having the following code

 type Transaction struct{
      Id string `bson:"_id,omitempty"`
      TransId string 
 }

 func GetTransactionID() (id interface{}, err error){
  query := bson.M{}
  transId, err := dbEngine.Find("transactionId", WalletDB, query)
  //transId is []interface{} type
  id, err1 := transId.(Transaction)
  return transId, err
}

Find

package dbEngine 
func Find(collectionName,dbName string, query interface{})(result []interface{}, err error){
   collection := session.DB(dbName).C(collectionName)
   err = collection.Find(query).All(&result)
   return result, err
}

Problem

Error: invalid type assertion: transId.(string) (non-interface type []interface {} on left)

Any suggestion to change the []interface{} to Transaction type.

like image 342
karthick Avatar asked Mar 20 '23 17:03

karthick


1 Answers

You can't convert a slice of interface{}s into any single struct. Are you sure you don't really want a slice of Transactions (i.e. a []Transaction type)? If so, you'll have to loop over it and convert each one:

for _, id := range transId {
    id.(Transaction) // do something with this
}
like image 168
Evan Avatar answered Apr 02 '23 01:04

Evan