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

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

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

问题

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

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 是 []interface{} 类型
    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)

有没有建议将 `[]interface{}` 更改为 `Transaction` 类型的方法

<details>
<summary>英文:</summary>

I am started working in `Go`. Having the following code 

     type Transaction struct{
          Id string `bson:&quot;_id,omitempty&quot;`
          TransId string 
     }

     func GetTransactionID() (id interface{}, err error){
	  query := bson.M{}
	  transId, err := dbEngine.Find(&quot;transactionId&quot;, 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(&amp;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.



</details>


# 答案1
**得分**: 8

你不能将`interface{}`的切片转换为任何单个的结构体你确定你真的不想要一个`Transaction`的切片`[]Transaction`类型如果是这样你需要遍历它并逐个进行转换

```go
for _, id := range transId {
    id.(Transaction) // 对这个进行操作
}
英文:

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
}

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:

确定