如何将 []interface{} 转换为自定义类型 – Go 语言?

huangapple go评论131阅读模式
英文:

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

问题

我正在使用Go语言进行工作。以下是要翻译的代码:

  1. type Transaction struct{
  2. Id string `bson:"_id,omitempty"`
  3. TransId string
  4. }
  5. func GetTransactionID() (id interface{}, err error){
  6. query := bson.M{}
  7. transId, err := dbEngine.Find("transactionId", WalletDB, query)
  8. //transId 是 []interface{} 类型
  9. id, err1 := transId.(Transaction)
  10. return transId, err
  11. }
  12. ###Find
  13. package dbEngine
  14. func Find(collectionName,dbName string, query interface{})(result []interface{}, err error){
  15. collection := session.DB(dbName).C(collectionName)
  16. err = collection.Find(query).All(&result)
  17. return result, err
  18. }
  19. ###Problem
  20. `Error:` invalid type assertion: transId.(string) (non-interface type []interface {} on left)
  21. 有没有建议将 `[]interface{}` 更改为 `Transaction` 类型的方法
  22. <details>
  23. <summary>英文:</summary>
  24. I am started working in `Go`. Having the following code
  25. type Transaction struct{
  26. Id string `bson:&quot;_id,omitempty&quot;`
  27. TransId string
  28. }
  29. func GetTransactionID() (id interface{}, err error){
  30. query := bson.M{}
  31. transId, err := dbEngine.Find(&quot;transactionId&quot;, WalletDB, query)
  32. //transId is []interface{} type
  33. id, err1 := transId.(Transaction)
  34. return transId, err
  35. }
  36. ###Find
  37. package dbEngine
  38. func Find(collectionName,dbName string, query interface{})(result []interface{}, err error){
  39. collection := session.DB(dbName).C(collectionName)
  40. err = collection.Find(query).All(&amp;result)
  41. return result, err
  42. }
  43. ###Problem
  44. `Error:` invalid type assertion: transId.(string) (non-interface type []interface {} on left)
  45. Any suggestion to change the `[]interface{}` to `Transaction` type.
  46. </details>
  47. # 答案1
  48. **得分**: 8
  49. 你不能将`interface{}`的切片转换为任何单个的结构体你确定你真的不想要一个`Transaction`的切片`[]Transaction`类型如果是这样你需要遍历它并逐个进行转换
  50. ```go
  51. for _, id := range transId {
  52. id.(Transaction) // 对这个进行操作
  53. }
英文:

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:

  1. for _, id := range transId {
  2. id.(Transaction) // do something with this
  3. }

huangapple
  • 本文由 发表于 2014年4月30日 19:41:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/23387155.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定