将Emtpy接口转换为Golang中的等效类型

时间:2018-10-10 12:07:55

标签: go mgo

将动态接口转换为其等效类型。例如,如果value为int,则应返回int;如果为string,则应返回int。

代码示例:

var options = bson.M{}
for _, val := range conditions {
    var attr, operator, value interface{}
    cons := val.(map[interface{}]interface{})

    for range cons {
        attr     = cons["attribute"]
        operator = cons["operator"]
        value    = cons["value"]
        switch operator {
            case "==":
                operator = "$eq"
            case "!=":
                operator = "$ne"
            case "()":
                operator = "$in"
                value = []string{fmt.Sprintf("%v", value)}
        }
        options[attr.(string)] = bson.M{operator.(string): value. 
        (int)}
    }
}

条件以以下格式显示。

conditions []interface{}
cons = append(cons, map[interface{}]interface{}{"attribute": 
"discontinued", "operator": "!=", "value": 1})

cons = append(cons, map[interface{}]interface{}{"attribute": "status", 
"operator": "==", "value": 1})

cons = append(cons, map[interface{}]interface{}{"attribute": 
"visibility", "operator": "==", "value": 4})

但是“值”:4 “值”:1 不确定。

抛出错误: 接口转换:interface {}是字符串,而不是int

1 个答案:

答案 0 :(得分:1)

您可以使用类型断言实现递归以获取接口的基础值。实现一个Switch案例,然后递归调用它,直到找到未知类型的原始类型。因为如果您要在接口内解析任何内容,则肯定会属于以下类型。

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays // slice of interface{}
map[string]interface{}, for JSON objects
nil for JSON null

检查以下有关如何实现该方法的代码。

package main

import (
    "fmt"
)

func main() {
     res, err := g.Execute( // Sends a query to Gremlin Server with bindings
           "g.V(x)",
            map[string]string{"x": "1234"},
            map[string]string{},
     )
     if err != nil {
          fmt.Println(err)
          return
     }
     fetchValue(res)
}

func fetchValue(value interface{}) {
    switch value.(type) {
    case string:
        fmt.Printf("%v is an interface \n ", value)
    case bool:
        fmt.Printf("%v is bool \n ", value)
    case float64:
        fmt.Printf("%v is float64 \n ", value)
    case []interface{}:
        fmt.Printf("%v is a slice of interface \n ", value)
        for _, v := range value.([]interface{}) { // use type assertion to loop over []interface{}
            fetchValue(v)
        }
    case map[string]interface{}:
        fmt.Printf("%v is a map \n ", value)
        for _, v := range value.(map[string]interface{}) { // use type assertion to loop over map[string]interface{}
            fetchValue(v)
        }
    default:
        fmt.Printf("%v is unknown \n ", value)
    }
}