英文:
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:"_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.
</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 Transaction
s (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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论